Options
All
  • Public
  • Public/Protected
  • All
Menu

Package muster

Muster Logo

Muster · CircleCI Known Vulnerabilities PRs Welcome GitHub license lerna codecov Greenkeeper badge

A universal data layer for components and services

https://dwstech.github.io/muster/

This is the monorepo for muster and muster-* packages.

Usage

The packages are published as separate NPM packages, so can be installed and imported separately.

npm install @dws/muster
npm install @dws/muster-react

yarn add @dws/muster @dws/muster-react

import muster from '@dws/muster';
import { container } from '@dws/muster-react';

Development

yarn

See CONTRIBUTING.md for details.

Licence

MIT

Index

Classes

Interfaces

Type aliases

Variables

Functions

Object literals

Type aliases

AcceptedPredicateTypes

AcceptedPredicateTypes: function | string | Array<string>

ActionCache

ActionCache: object & object | object

ActionCacheQueueItem

ActionCacheQueueItem: object

Type declaration

ActionId

ActionId: NodeId & OperationId

AddItemAttableGraphNode

AddItemAttableGraphNode: DynamicGraphNode<T, P, S, D, V, "addItemAt", AddItemAtOperation, AddItemAttableNodeType<T, P, S, D, V>>

AddItemAttableNodeDefinition

AddItemAttableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "addItemAt", AddItemAtOperation, AddItemAttableNodeType<T, P, S, D, V>>

AddItemAttableNodeType

AddItemAttableNodeType: DynamicNodeType<T, P, S, D, V, "addItemAt", AddItemAtOperation>

AnyRequest

ArrayReducerAccumulator

ArrayReducerAccumulator: Array<GraphNode>

BranchDefinition

BranchDefinition: object

Type declaration

CachedActionId

CachedActionId: number

CallArgument

CallArgument: NodeDefinition | GraphNode

CallArgumentArray

CallArgumentArray: Array<CallArgument>

CallArgumentMap

CallArgumentMap: object

Type declaration

CallableGraphNode

CallableGraphNode: DynamicGraphNode<T, P, S, D, V, "call", CallOperation, CallableNodeType<T, P, S, D, V>>

CallableNodeDefinition

CallableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "call", CallOperation, CallableNodeType<T, P, S, D, V>>

CallableNodeType

CallableNodeType: DynamicNodeType<T, P, S, D, V, "call", CallOperation>

Callback

Callback: function

Type declaration

    • (err: any, response: T, body: any): void
    • Parameters

      • err: any
      • response: T
      • body: any

      Returns void

ChildKey

ChildKey: any

ChildKeyDefinition

ClearableGraphNode

ClearableGraphNode: DynamicGraphNode<T, P, S, D, V, "clear", ClearOperation, ClearableNodeType<T, P, S, D, V>>

ClearableNodeDefinition

ClearableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "clear", ClearOperation, ClearableNodeType<T, P, S, D, V>>

ClearableNodeType

ClearableNodeType: DynamicNodeType<T, P, S, D, V, "clear", ClearOperation>

ContainerGraphNode

ContainerGraphNode: DynamicGraphNode<T, P, S, D, V, "getChild", GetChildOperation, ContainerNodeType<T, P, S, D, V>>

ContainerNodeDefinition

ContainerNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "getChild", GetChildOperation, ContainerNodeType<T, P, S, D, V>>

ContainerNodeType

ContainerNodeType: DynamicNodeType<T, P, S, D, V, "getChild", GetChildOperation>

ContainsableGraphNode

ContainsableGraphNode: DynamicGraphNode<T, P, S, D, V, "contains", ContainsOperation, ContainsableNodeType<T, P, S, D, V>>

ContainsableNodeDefinition

ContainsableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "contains", ContainsOperation, ContainsableNodeType<T, P, S, D, V>>

ContainsableNodeType

ContainsableNodeType: DynamicNodeType<T, P, S, D, V, "contains", ContainsOperation>

ContextDependency

ContextId

ContextId: string

ContextName

ContextName: string

ContextValues

ContextValues: object

Type declaration

ContextValuesDefinitions

ContextValuesDefinitions: object

Type declaration

ContextWithPathKey

ContextWithPathKey: Context & object

DataNode

DataNode: ValueNode<any> | OkNode | NilNode | QuoteNode | ErrorNode

DataNodeDefinition

DeferNodeFallbackGenerator

DeferNodeFallbackGenerator: function

Type declaration

DisposeCallback

DisposeCallback: function

Type declaration

    • (): void
    • Returns void

DisposeCallback

DisposeCallback: function

Type declaration

    • (): void
    • Returns void

DisposeRequest

DisposeRequest: function

Type declaration

    • (): void
    • Returns void

DynamicNodeType

DynamicNodeType: StatelessNodeType<T, P, V, M, O> | StatefulNodeType<T, P, S, D, V, M, O>

EmitterCallback

EmitterCallback: function

Type declaration

    • (event: T): void
    • Parameters

      • event: T

      Returns void

ErrorFallbackGenerator

ErrorFallbackGenerator: function

Type declaration

EvaluableGraphNode

EvaluableGraphNode: DynamicGraphNode<T, P, S, D, V, "evaluate", EvaluateOperation, EvaluableNodeType<T, P, S, D, V>>

EvaluableNodeDefinition

EvaluableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "evaluate", EvaluateOperation, EvaluableNodeType<T, P, S, D, V>>

EvaluableNodeType

EvaluableNodeType: DynamicNodeType<T, P, S, D, V, "evaluate", EvaluateOperation>

EventRedispatcher

EventRedispatcher: function

Type declaration

ExclusiveSliceBounds

ExclusiveSliceBounds: object

Type declaration

FieldDefinition

FieldSetDefinition

FieldSetDefinition: object

Type declaration

FormatData

FormatData: Array<[string, NodeDefinition]>

GetterFactory

GetterFactory: function

Type declaration

GraphNodeWithIsPending

GraphNodeWithIsPending: DynamicGraphNode<T, P, S, D, V, "isPending", IsPendingOperation, NodeTypeWithIsPending<T, P, S, D, V>>

GraphNodeWithIsUpdating

GraphNodeWithIsUpdating: DynamicGraphNode<T, P, S, D, V, "isUpdating", IsUpdatingOperation, NodeTypeWithIsUpdating<T, P, S, D, V>>

GraphNodeWithRemoveItem

GraphNodeWithRemoveItem: DynamicGraphNode<T, P, S, D, V, "removeItem", RemoveItemOperation, NodeTypeWithRemoveItem<T, P, S, D, V>>

HashSet

HashSet: Set<string>

HistoryWithId

HistoryWithId: History & object

InclusiveSliceBounds

InclusiveSliceBounds: object

Type declaration

InitableGraphNode

InitableGraphNode: DynamicGraphNode<T, P, S, D, V, "init", InitOperation, InitableNodeType<T, P, S, D, V>>

InitableNodeDefinition

InitableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "init", InitOperation, InitableNodeType<T, P, S, D, V>>

InitableNodeType

InitableNodeType: DynamicNodeType<T, P, S, D, V, "init", InitOperation>

InvalidTypeErrorOptions

InvalidTypeErrorOptions: object

Type declaration

  • Optional expected?: any | Array<any>
  • received: any

InvalidateOnNodeCallback

InvalidateOnNodeCallback: function

Type declaration

IterableGraphNode

IterableGraphNode: DynamicGraphNode<T, P, S, D, V, "iterate", IterateOperation, IterableNodeType<T, P, S, D, V>>

IterableNodeDefinition

IterableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "iterate", IterateOperation, IterableNodeType<T, P, S, D, V>>

IterableNodeType

IterableNodeType: DynamicNodeType<T, P, S, D, V, "iterate", IterateOperation>

KeyMatcher

KeyMatcher: function

Type declaration

LegacyDataNode

LegacyDataNode: DataNode | TreeNode | ArrayNode

LegacyDataNodeDefinition

LengthtableGraphNode

LengthtableGraphNode: DynamicGraphNode<T, P, S, D, V, "length", LengthOperation, LengthtableNodeType<T, P, S, D, V>>

LengthtableNodeDefinition

LengthtableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "length", LengthOperation, LengthtableNodeType<T, P, S, D, V>>

LengthtableNodeType

LengthtableNodeType: DynamicNodeType<T, P, S, D, V, "length", LengthOperation>

ListGraphNode

ListGraphNode: DynamicGraphNode<T, P, S, D, V, "getItems", GetItemsOperation, ListNodeType<T, P, S, D, V>>

ListKeyNode

ListKeyNodeDefinition

ListNodeDefinition

ListNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "getItems", GetItemsOperation, ListNodeType<T, P, S, D, V>>

ListNodeType

ListNodeType: DynamicNodeType<T, P, S, D, V, "getItems", GetItemsOperation>

LocationParamsEncoding

LocationParamsEncoding: "base64" | "json"

LogSink

LogSink: function

Type declaration

    • (...args: Array<any>): void
    • Parameters

      • Rest ...args: Array<any>

      Returns void

MiddlewareTransformer

MiddlewareTransformer: function

Type declaration

ModuleDependencies

ModuleDependencies: object

Type declaration

ModuleFactory

ModuleFactory: function

Type declaration

ModuleRequirements

ModuleRequirements: object

Type declaration

  • [name: string]: Type

MusterEventName

MusterEventName: string

MusterEventPayload

MusterEventPayload: any

MusterEventSource

MusterEventSource: EventEmitter<MusterEvent<T, V>>

MusterOperationDefinition

MusterOperationDefinition: Operation<MusterScenarioInput, MusterScenarioOutput, NodeDefinition | Array<NodeDefinition>>

MusterScenarioDefinition

MusterScenarioState

MusterScenarioState: Muster

MusterTypeMap

MusterTypeMap: object

Type declaration

MusterTypeName

MusterTypeName: string

NamedFnArgs

NamedFnArgs: object

Type declaration

NodeData

NodeData: object

Type declaration

  • [key: string]: any

NodeDefinitionCallback

NodeDefinitionCallback: function

Type declaration

NodeDefinitionWithIsPending

NodeDefinitionWithIsPending: DynamicNodeDefinition<T, P, S, D, V, "isPending", IsPendingOperation, NodeTypeWithIsPending<T, P, S, D, V>>

NodeDefinitionWithIsUpdating

NodeDefinitionWithIsUpdating: DynamicNodeDefinition<T, P, S, D, V, "isUpdating", IsUpdatingOperation, NodeTypeWithIsUpdating<T, P, S, D, V>>

NodeDefinitionWithRemoveItem

NodeDefinitionWithRemoveItem: DynamicNodeDefinition<T, P, S, D, V, "removeItem", RemoveItemOperation, NodeTypeWithRemoveItem<T, P, S, D, V>>

NodeId

NodeId: string

NodeLike

NodeLike: any

NodeLikeCallArgument

NodeLikeCallArgument: NodeLike | NodeDefinition | GraphNode

NodeLikeCallArgumentArray

NodeLikeCallArgumentArray: Array<NodeLikeCallArgument>

NodeLikeCallArgumentMap

NodeLikeCallArgumentMap: object

Type declaration

NodeName

NodeName: string

NodeProperties

NodeProperties: object

Type declaration

NodeState

NodeState: any

NodeStream

NodeStream: Stream<T>

NodeTransformer

NodeTransformer: function

Type declaration

NodeType

NodeType: StaticNodeType<T, P, V> | DynamicNodeType<T, P, S, D, V, M, O>

NodeTypeDefinition

NodeTypeDefinition: StaticNodeTypeDefinition<P, V> | StatelessNodeTypeDefinition<T, P, V, M> | StatefulNodeTypeDefinition<T, P, S, D, V, M>

NodeTypeMap

NodeTypeMap: object

Type declaration

NodeTypeWithIsPending

NodeTypeWithIsPending: DynamicNodeType<T, P, S, D, V, "isPending", IsPendingOperation>

NodeTypeWithIsUpdating

NodeTypeWithIsUpdating: DynamicNodeType<T, P, S, D, V, "isUpdating", IsUpdatingOperation>

NodeTypeWithRemoveItem

NodeTypeWithRemoveItem: DynamicNodeType<T, P, S, D, V, "removeItem", RemoveItemOperation>

OnNodeCallback

OnNodeCallback: function

Type declaration

OperationFactory

OperationFactory: function

Type declaration

OperationHandler

OperationHandler: StatelessOperationHandler<T, P, V, M, O> | StatefulOperationHandler<T, P, S, D, V, M, O>

OperationHandlerDefinition

OperationHandlerDefinition: StatelessOperationHandlerDefinition<T, P, V, M> | StatefulOperationHandlerDefinition<T, P, S, D, V, M>

OperationId

OperationId: string

OperationName

OperationName: string

OperationProperties

OperationProperties: object

Type declaration

OperationTypeMap

OperationTypeMap: object

Type declaration

PathKey

PathKey: string | GraphNode | ListKeyNode

PendingFallbackGenerator

PendingFallbackGenerator: function

Type declaration

PoptableGraphNode

PoptableGraphNode: DynamicGraphNode<T, P, S, D, V, "pop", PopOperation, PoptableNodeType<T, P, S, D, V>>

PoptableNodeDefinition

PoptableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "pop", PopOperation, PoptableNodeType<T, P, S, D, V>>

PoptableNodeType

PoptableNodeType: DynamicNodeType<T, P, S, D, V, "pop", PopOperation>

PushtableGraphNode

PushtableGraphNode: DynamicGraphNode<T, P, S, D, V, "push", PushOperation, PushtableNodeType<T, P, S, D, V>>

PushtableNodeDefinition

PushtableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "push", PushOperation, PushtableNodeType<T, P, S, D, V>>

PushtableNodeType

PushtableNodeType: DynamicNodeType<T, P, S, D, V, "push", PushOperation>

QueriesSnapshot

QueriesSnapshot: object

Type declaration

QueryPartCallback

QueryPartCallback: function

Type declaration

QuerySetCallback

QuerySetCallback: function

Type declaration

QuerySetChild

QuerySetChildWithPath

QuerySetChildWithPath: object

Type declaration

RelativeSliceBounds

RelativeSliceBounds: object

Type declaration

RemoveItemAttableGraphNode

RemoveItemAttableGraphNode: DynamicGraphNode<T, P, S, D, V, "removeItemAt", RemoveItemAtOperation, RemoveItemAttableNodeType<T, P, S, D, V>>

RemoveItemAttableNodeDefinition

RemoveItemAttableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "removeItemAt", RemoveItemAtOperation, RemoveItemAttableNodeType<T, P, S, D, V>>

RemoveItemAttableNodeType

RemoveItemAttableNodeType: DynamicNodeType<T, P, S, D, V, "removeItemAt", RemoveItemAtOperation>

RequestGraphNode

RequestGraphNode: DynamicGraphNode<T, P, S, D, V, "request", RequestOperation, RequestNodeType<T, P, S, D, V>>

RequestMetadata

RequestMetadata: object

Type declaration

  • [namespace: string]: any

RequestNodeDefinition

RequestNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "request", RequestOperation, RequestNodeType<T, P, S, D, V>>

RequestNodeType

RequestNodeType: DynamicNodeType<T, P, S, D, V, "request", RequestOperation>

ResettableGraphNode

ResettableGraphNode: DynamicGraphNode<T, P, S, D, V, "reset", ResetOperation, ResettableNodeType<T, P, S, D, V>>

ResettableNodeDefinition

ResettableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "reset", ResetOperation, ResettableNodeType<T, P, S, D, V>>

ResettableNodeType

ResettableNodeType: DynamicNodeType<T, P, S, D, V, "reset", ResetOperation>

ResolvableGraphNode

ResolvableGraphNode: DynamicGraphNode<T, P, S, D, V, "resolve", ResolveOperation, ResolvableNodeType<T, P, S, D, V>>

ResolvableNodeDefinition

ResolvableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "resolve", ResolveOperation, ResolvableNodeType<T, P, S, D, V>>

ResolvableNodeType

ResolvableNodeType: DynamicNodeType<T, P, S, D, V, "resolve", ResolveOperation>

ResponseAssembler

ResponseAssembler: function

Type declaration

ResponseFactory

ResponseFactory: function

Type declaration

ResponsePartAssembler

ResponsePartAssembler: function

Type declaration

ResponseTransformer

ResponseTransformer: function

Type declaration

ResultableGraphNode

ResultableGraphNode: DynamicGraphNode<T, P, S, D, V, "result", ResultOperation<any>, ResultableNodeType<T, P, S, D, V>>

ResultableNodeDefinition

ResultableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "result", ResultOperation<any>, ResultableNodeType<T, P, S, D, V>>

ResultableNodeType

ResultableNodeType: DynamicNodeType<T, P, S, D, V, "result", ResultOperation<any>>

SchedulerFactory

SchedulerFactory: function

Type declaration

ScopeId

ScopeId: string

SerializableObject

SerializableObject: NodeDefinition | GraphOperation | Matcher<any, any>

SerializableQuerySetChild

SerializedActionCache

SerializedActionCache: object & object | object

SerializedContext

SerializedContext: ContextId

SerializedGraphOperation

SerializedGraphOperation: object

Type declaration

  • $operation: O["name"]
  • data: P
  • id: string

SerializedMusterTypeData

SerializedMusterTypeData: any

SerializedNodeDefinition

SerializedNodeDefinition: object

Type declaration

  • $type: N["name"]
  • data: V

SerializedNodeProperties

SerializedNodeProperties: any

SerializedNodeType

SerializedNodeType: object

Type declaration

  • operations: Array<string>

SerializedNodeTypesMap

SerializedNodeTypesMap: object

Type declaration

SerializedOperationProperties

SerializedOperationProperties: any

SerializedPrimitive

SerializedPrimitive: string | number | boolean | null | undefined

SerializedScope

SerializedScope: ScopeId

SerializedSubscription

SerializedSubscription: object

Type declaration

SerializedValue

SettableGraphNode

SettableGraphNode: DynamicGraphNode<T, P, S, D, V, "set", SetOperation, SettableNodeType<T, P, S, D, V>>

SettableNodeDefinition

SettableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "set", SetOperation, SettableNodeType<T, P, S, D, V>>

SettableNodeType

SettableNodeType: DynamicNodeType<T, P, S, D, V, "set", SetOperation>

SetterFactory

SetterFactory: function

Type declaration

ShapeFields

ShapeFields: object

Type declaration

ShifttableGraphNode

ShifttableGraphNode: DynamicGraphNode<T, P, S, D, V, "shift", ShiftOperation, ShifttableNodeType<T, P, S, D, V>>

ShifttableNodeDefinition

ShifttableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "shift", ShiftOperation, ShifttableNodeType<T, P, S, D, V>>

ShifttableNodeType

ShifttableNodeType: DynamicNodeType<T, P, S, D, V, "shift", ShiftOperation>

SortValue

SortValue: null | undefined | boolean | string | number | Date

SteppableGraphNode

SteppableGraphNode: DynamicGraphNode<T, P, S, D, V, "step", StepOperation<any>, SteppableNodeType<T, P, S, D, V>>

SteppableNodeDefinition

SteppableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "step", StepOperation<any>, SteppableNodeType<T, P, S, D, V>>

SteppableNodeType

SteppableNodeType: DynamicNodeType<T, P, S, D, V, "step", StepOperation<any>>

StoreSubscribe

StoreSubscribe: function

Type declaration

StreamFactory

StreamFactory: function

Type declaration

StreamUpdateCallback

StreamUpdateCallback: function

Type declaration

    • (value: T): void
    • Parameters

      • value: T

      Returns void

SupportsRemoveItemsGraphNode

SupportsRemoveItemsGraphNode: DynamicGraphNode<T, P, S, D, V, "removeItems", RemoveItemsOperation, SupportsRemoveItemsNodeType<T, P, S, D, V>>

SupportsRemoveItemsNodeDefinition

SupportsRemoveItemsNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "removeItems", RemoveItemsOperation, SupportsRemoveItemsNodeType<T, P, S, D, V>>

SupportsRemoveItemsNodeType

SupportsRemoveItemsNodeType: DynamicNodeType<T, P, S, D, V, "removeItems", RemoveItemsOperation>

TransformOperation

TransformOperation: InitOperation | StepOperation<any> | ResultOperation<any>

TransformerGraphNode

TransformerGraphNode

TransformerGraphNode: DynamicGraphNode<T, P, S, D, V, "transformItems", TransformItemsOperation, TransformerNodeType<T, P, S, D, V>>

TransformerNodeDefinition

TransformerNodeDefinition

TransformerNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "transformItems", TransformItemsOperation, TransformerNodeType<T, P, S, D, V>>

TransformerNodeType

TransformerNodeType: DynamicNodeType<T, P, S, D, V, "transformItems", TransformItemsOperation>

Type

Type: true

UnshifttableGraphNode

UnshifttableGraphNode: DynamicGraphNode<T, P, S, D, V, "unshift", UnshiftOperation, UnshifttableNodeType<T, P, S, D, V>>

UnshifttableNodeDefinition

UnshifttableNodeDefinition: DynamicNodeDefinition<T, P, S, D, V, "unshift", UnshiftOperation, UnshifttableNodeType<T, P, S, D, V>>

UnshifttableNodeType

UnshifttableNodeType: DynamicNodeType<T, P, S, D, V, "unshift", UnshiftOperation>

UnsubscribeCallback

UnsubscribeCallback: function

Type declaration

    • (): void
    • Returns void

UpdateCallback

UpdateCallback: function

Type declaration

UpdateCallback

UpdateCallback: function

Type declaration

ValueStream

ValueStream: ObservableLike<NodeDefinition | NodeLike>

ValueStreamFactory

ValueStreamFactory: function

Type declaration

ValueUpdater

ValueUpdater: Partial<object> | function

XhrResult

XhrResult: object | object

YieldedValueType

YieldedValueType: NodeMap | ProxiedNode | DataNode | NodeLike | Array<ProxiedNode | DataNode | NodeLike>

Variables

Const ActionNodeType

ActionNodeType: StatelessNodeType<"action", ActionNodeProperties> = createNodeType<'action',ActionNodeProperties>('action', {serialize: false,deserialize: false,shape: {body: types.saveHash(types.func),},operations: {call: {cacheable: false,getDependencies(properties: ActionNodeProperties,operation: CallOperation,): Array<NodeDependency> {const { args } = operation.properties;if (!args) return [];if (isCallArgumentArray(args)) {return args.map((arg) => ({target: arg,until: untilIsDataNode,once: true,}));}return Object.keys(args).map((name) => ({target: args[name],until: untilIsDataNode,once: true,}));},run(node: ActionNode,operation: CallOperation,argValues: Array<DataNode>,): GraphNode | NodeDefinition {const { body } = node.definition.properties;const { args } = operation.properties;const unwrappedArgs = argValues.map((argValue) => valueOf(argValue));let result: any;if (!args) {result = body();} else if (isCallArgumentArray(args)) {// Handle array of argumentsresult = body(...unwrappedArgs);} else {// Handle named argumentsconst argNames = Object.keys(args);result = body(fromPairs(zip(argNames, unwrappedArgs)));}if (isProxiedNode(result)) {return getProxiedNodeValue(result);}if (isGraphNode(result)) {return result;}if (isNodeDefinition(result)) {return withScopeFrom(node, result);}if (isGenerator(result)) {const generatorResult = stepNext(result, []);return isGraphNode(generatorResult)? generatorResult: withScopeFrom(node, generatorResult);}return withScopeFrom(node, value(result));},},},})

The implementation of the action. See the action documentation for more information.

Const AddItemAtNodeType

AddItemAtNodeType: StatefulNodeType<"add-item-at", AddItemAtNodeProperties, AddItemAtNodeState, __type> = createNodeType<'add-item-at', AddItemAtNodeProperties, AddItemAtNodeState, {}>('add-item-at', {shape: {index: graphTypes.nodeDefinition,item: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,},state: {memoized: types.saveHash(types.func),},getInitialState() {return {memoized: once((target: GraphNode, item: NodeDefinition, index: number) =>createGraphAction(target, addItemAtOperation(item, index)),),};},operations: {evaluate: {cacheable: false,getDependencies({ target, index }: AddItemAtNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsAddItemAtOperation,},{target: index,until: untilIntegerValueIndex,},];},run(node: AddItemAtNode,options: never,[target, index]: [GraphNode, ValueNode<number>],context: never,state: AddItemAtNodeState,): GraphAction {const { item } = node.definition.properties;return state.memoized(target, item, index.definition.properties.value);},},},})

The implementation of the addItemAt node. See the addItemAt documentation for more information.

Const AddItemAtOperationType

AddItemAtOperationType: OperationType<"addItemAt", AddItemAtProperties> = createOperationType<'addItemAt', AddItemAtProperties>('addItemAt', {cacheable: false,shape: {index: types.number,value: graphTypes.nodeDefinition,},})

An implementation of the addItemAtOperation. See the addItemAtOperation documentation to find out more.

Const AddNodeType

AddNodeType: StatelessNodeType<"add", AddNodeProperties> = createNodeType<'add',AddNodeProperties>('add', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: AddNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(AddNodeType, 'operand'),}));},run(node: AddNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {const operandValues = operands.map((operand) => operand.definition.properties.value);return value(operandValues.reduce((total, value) => total + value, 0));},},},})

The implementation of the add node. See the add documentation to learn more.

Const AndNodeType

AndNodeType: StatelessNodeType<"and", AndNodeProperties> = createNodeType<'and',AndNodeProperties>('and', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: AndNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('And node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: AndNode, options: never, operands: Array<ValueNode<any>>): NodeDefinition {return value(operands.every((operand) => Boolean(operand.definition.properties.value)));},},},})

The implementation of the and node. See the and documentation to learn more.

Const ApplyNodeType

ApplyNodeType: StatelessNodeType<"apply", ApplyNodeProperties> = createNodeType<'apply',ApplyNodeProperties>('apply', {shape: {target: types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),args: types.oneOfType([types.arrayOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),types.objectOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),]),},operations: {evaluate: {getDependencies({ target }: ApplyNodeProperties): [NodeDependency] {return [{target,until: untilSupportsCallOperation,},];},run(node: ApplyNode, options: never, [subjectNode]: [CallableGraphNode]): GraphAction {const { args } = node.definition.properties;let argNodes: any;if (isCallArgumentArray(args)) {argNodes = args.map((arg) => (isGraphNode(arg) ? arg : withScopeFrom(node, arg)));} else {argNodes = mapValues(args, (arg) => (isGraphNode(arg) ? arg : withScopeFrom(node, arg)));}return createGraphAction(subjectNode, callOperation(argNodes));},},},})

The implementation of the apply node. See the apply documentation for more information.

Const ApplyTransformsNodeType

ApplyTransformsNodeType: StatelessNodeType<"applyTransforms", ApplyTransformsNodeProperties> = createNodeType<'applyTransforms', ApplyTransformsNodeProperties>('applyTransforms', {shape: {target: graphTypes.nodeDefinition,transforms: types.arrayOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),},operations: {getItems: {getDependencies({ target }: ApplyTransformsNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsGetItemOperation,},];},run(node: ApplyTransformsNode,operation: GetItemsOperation,[source]: [GraphNode],): GraphAction {const { transforms } = node.definition.properties;const scopedTransforms = [...transforms, ...operation.properties.transforms].map((transform) => (isNodeDefinition(transform) ? withScopeFrom(node, transform) : transform),);return createGraphAction(source, getItemsOperation(scopedTransforms));},},},})

The implementation of the applyTransforms node. See the applyTransforms documentation to learn more.

Const ArithmeticNodeTypes

ArithmeticNodeTypes: Array<NodeType> = [AddNodeType,CeilNodeType,ClampNodeType,DivideNodeType,FloorNodeType,MaxNodeType,MinNodeType,ModNodeType,MultiplyNodeType,PowNodeType,RoundNodeType,SqrtNodeType,SubtractNodeType,]

Const ArrayListNodeType

ArrayListNodeType: StatefulNodeType<"arrayList", ArrayListNodeProperties, ArrayListNodeState, ArrayListNodeData> = createNodeType<'arrayList', ArrayListNodeProperties, ArrayListNodeState, ArrayListNodeData>('arrayList',{state: {items: types.optional(graphTypes.nodeDefinition),poppedItem: types.optional(graphTypes.graphNode),shiftedItem: types.optional(graphTypes.graphNode),unshiftedItem: types.optional(graphTypes.graphNode),removeItems: types.objectOf(graphTypes.nodeDefinition),},shape: {items: types.arrayOf(graphTypes.nodeDefinition),},getInitialState(): ArrayListNodeState {return {items: undefined,poppedItem: undefined,shiftedItem: undefined,unshiftedItem: undefined,removeItems: {},};},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,) {if (this.getState().items) return;this.retain();this.setState((state) => ({...state,items: nodeList(node.definition.properties.items.map((item) => withUniqueId(node, item))),}));},operations: {addItemAt: {cacheable: false,run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,operation: AddItemAtOperation,): void {const { index, value } = operation.properties;const clonedItems = this.getState().items!.properties.items.slice(0);const sanitizedIndex = Math.min(clonedItems.length - 1, index);clonedItems.splice(sanitizedIndex, 0, withUniqueId(node, value));this.setState((state) => ({...state,items: nodeList(clonedItems),}));},},clear: {cacheable: false,run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,): void {this.setState((state) => ({...state,items: nodeList([]),}));},},evaluate: {run(node: ArrayListNode,options: never,dependencies: Array<never>,context: Array<never>,state: ArrayListNodeState,): NodeDefinition {return state.items!;},},length: {run(node: ArrayListNode,options: never,dependencies: Array<never>,context: Array<never>,state: ArrayListNodeState,): NodeDefinition {return value(state.items!.properties.items.length);},},contains: {run(node: ArrayListNode,operation: ContainsOperation,dependencies: Array<never>,contextDependencies: Array<never>,state: ArrayListNodeState,): NodeDefinition {const { item: otherItem, comparator } = operation.properties;return resolve(state.items!.properties.items.map((item) => ({target: apply([item, otherItem], comparator),until: untilBooleanValuePredicate,})),(results: Array<ValueNode<boolean>>) =>value(results.some((item) => item.definition.properties.value)),);},},pop: {cacheable: false,run(node: ArrayListNode,options: never,dependencies: Array<never>,context: Array<never>,state: ArrayListNodeState,): GraphNode {return state.poppedItem!;},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,): void {const items = this.getState().items!.properties.items;if (items.length === 0) {this.setState((state) => ({...state,poppedItem: withScopeFrom(node, nil()),}));return;}const remaining = items.slice(0);const last = remaining.pop()!;this.setState((state) => ({...state,items: nodeList(remaining),poppedItem: last,}));},},push: {cacheable: false,run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,operation: PushOperation,): void {const { items } = this.getState().items!.properties;this.setState((state) => ({...state,items: nodeList([...items, withUniqueId(node, operation.properties.value)]),}));},},removeItem: {cacheable: false,run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,operation: RemoveItemOperation,): void {const { items } = this.getState().items!.properties;const clonedItems = items.slice(0);const itemIndex = clonedItems.findIndex((item) => item.definition.properties.id === operation.properties.id,);if (itemIndex === -1) return;clonedItems.splice(itemIndex, 1);this.setState((state) => ({...state,items: nodeList(clonedItems),}));},},removeItemAt: {cacheable: false,run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,operation: RemoveItemAtOperation,): void {const { index } = operation.properties;const { items } = this.getState().items!.properties;if (!Number.isInteger(index) || index < 0 || index > items.length - 1) return;this.setState((state) => ({...state,items: nodeList([...items.slice(0, operation.properties.index),...items.slice(operation.properties.index + 1),]),}));},},removeItems: {cacheable: false,run(node: ArrayListNode,operation: RemoveItemsOperation,dependencies: Array<never>,contextDependencies: Array<never>,state: ArrayListNodeState,): NodeDefinition {const { removeItems } = state;return removeItems[operation.id] || ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,operation: RemoveItemsOperation,): void {const { predicate } = operation.properties;const { items } = this.getState().items!.properties;if (items.length === 0) {return;}this.setState((prevState) =>operation.id in prevState.removeItems? prevState: {...prevState,removeItems: {...prevState.removeItems,[operation.id]: resolve(items.map((item) => ({target: apply([item], predicate),until: untilBooleanValuePredicate,})),(processedResults: Array<ValueNode<boolean>>) => {this.setState((prevState) => {// If the array list has been mutated since this operation was subscribed, there// may now be some items which haven't been tested. These should NOT be removed.const { items: currentItems } = this.getState();const updatedItems = currentItems!.properties.items.filter((item, index) => {const processedItemIndex = items.findIndex((processedItem) => processedItem.id === item.id,);if (processedItemIndex === -1) {return true;}const result = processedResults[processedItemIndex];return !result.definition.properties.value;},);return {...prevState,items: nodeList(updatedItems),removeItems: omit(prevState.removeItems, operation.id),};});return ok();},),},},);},},shift: {cacheable: false,run(node: ArrayListNode,options: never,dependencies: Array<never>,context: Array<never>,state: ArrayListNodeState,): GraphNode {return state.shiftedItem!;},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,): void {const { items } = this.getState().items!.properties;if (!items || items.length === 0) {this.setState((state) => ({...state,shiftedItem: withScopeFrom(node, nil()),}));return;}const remaining = items.slice(0);const last = remaining.shift()!;this.setState((state) => ({...state,items: nodeList(remaining),shiftedItem: last,}));},},unshift: {cacheable: false,run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<ArrayListNodeState, ArrayListNodeData>,node: ArrayListNode,operation: UnshiftOperation,): void {const { items } = this.getState().items!.properties;this.setState((state) => ({...state,items: nodeList([withUniqueId(node, operation.properties.value), ...items]),}));},},},},)

The implementation of the arrayList node. See the arrayList documentation to learn more.

Const ArrayNodeType

ArrayNodeType: StatelessNodeType<"array", ArrayNodeProperties> = createNodeType<'array',ArrayNodeProperties>('array', {shape: {items: types.arrayOf(graphTypes.nodeDefinition),},operations: {getItems: {run(node: ArrayNode, operation: GetItemsOperation): NodeDefinition | GraphAction {const items = toGraphNodesWithIndices(node, node.definition.properties.items);const itemsNode = nodeList(items);return operation.properties.transforms.length === 0? itemsNode: createGraphAction(withScopeFrom(node, itemsNode), operation);},},iterate: {run(node: ArrayNode): NodeDefinition {const items = toGraphNodesWithIndices(node, node.definition.properties.items);if (items.length === 0) {return nil();}return iteratorResult(items[0], nodeList(items.slice(1)));},},length: {run(node: ArrayNode): NodeDefinition {return value(node.definition.properties.items.length);},},contains: {run(node: ArrayNode, operation: ContainsOperation): NodeDefinition {const items = toGraphNodesWithIndices(node, node.definition.properties.items);const { item: otherItem, comparator } = operation.properties;return resolve(items.map((item) => ({target: apply([item, otherItem], comparator),until: untilBooleanValueNodeItem,})),(results: Array<ValueNode<boolean>>) =>value(results.some((item) => item.definition.properties.value)),);},},},})

The implementation of the array. See the array documentation to learn more.

Const ArrayReducerNodeType

ArrayReducerNodeType: StatelessNodeType<"arrayReducer", ArrayReducerNodeProperties> = createNodeType('arrayReducer', {operations: {init: {run(): ValueNodeDefinition<ArrayReducerAccumulator> {return value([]);},},step: {run(node: ArrayReducerNode,operation: StepOperation<ArrayReducerAccumulator>,): ValueNodeDefinition<ArrayReducerAccumulator> {const { acc, item } = operation.properties;return value([...acc, item]);},},result: {run(node: ArrayReducerNode,operation: ResultOperation<ArrayReducerAccumulator>,): ValueNodeDefinition<NodeListNodeDefinition> {return value(nodeList(operation.properties.acc));},},},})

Const BatchRequestsMiddlewareNodeType

BatchRequestsMiddlewareNodeType: StatefulNodeType<"batch-requests-middleware", BatchRequestsMiddlewareNodeProperties, BatchRequestsMiddlewareNodeState, BatchRequestsMiddlewareNodeData> = createNodeType<'batch-requests-middleware',BatchRequestsMiddlewareNodeProperties,BatchRequestsMiddlewareNodeState,BatchRequestsMiddlewareNodeData>('batch-requests-middleware', {shape: {},state: {batcherResults: types.objectOf(graphTypes.nodeDefinition),},getInitialState() {return {batcherResults: {},};},onSubscribe() {this.setData({batchers: new Map(),});},onUnsubscribe() {const { batchers } = this.getData();if (!batchers) return;for (const batcher of batchers.values()) {batcher.dispose();}},operations: {request: {run(node: BatchRequestsMiddlewareNode,operation: RequestOperation,dependencies: never,context: never,state: BatchRequestsMiddlewareNodeState,): NodeDefinition | GraphNode {const { metadata, next, query } = operation.properties;if (!next) {return error('Missing `next` middleware.');}if (!isQuerySetNodeDefinition(query)) {return withScopeFrom(next, traverse(next.definition, requestOperation(query, metadata)));}return state.batcherResults[query.properties.root.id] || pending();},onSubscribe(this: NodeExecutionContext<BatchRequestsMiddlewareNodeState,BatchRequestsMiddlewareNodeData>,node: BatchRequestsMiddlewareNode,operation: RequestOperation,): void {const { metadata, next, query } = operation.properties;// Check if the query is of a supported type or the next middleware is undefinedif (!next || !isQuerySetNodeDefinition(query)) return;const batchers = this.getData().batchers!;const { children, root } = query.properties;let currentBatcher = batchers.get(root.id);if (!currentBatcher) {currentBatcher = new RequestBatcher((node, operation, callback) => node.scope.store.subscribe(node, operation, callback),next,root,(value) => {this.setState((state) => ({...state,batcherResults: {...state.batcherResults,[root.id]: value,},}));},);batchers.set(root.id, currentBatcher);}this.setState((state) => ({...state,batcherResults: omit(state.batcherResults, root.id),}));currentBatcher.setRequest(children as Array<SerializableQuerySetChild>, metadata);},onUnsubscribe(this: NodeExecutionContext<BatchRequestsMiddlewareNodeState,BatchRequestsMiddlewareNodeData>,node: BatchRequestsMiddlewareNode,operation: RequestOperation,): void {const { query } = operation.properties;if (!isQuerySetNodeDefinition(query)) return;const { root } = query.properties;this.setState((state) => ({...state,batcherResults: omit(state.batcherResults, root.id),}));},},},})

Const BrowserNodeTypes

BrowserNodeTypes: Array<NodeType> = [LocationNodeType,LocationDataNodeType,LocationPathNodeType,]

Const CACHED_INSTANCES

CACHED_INSTANCES: GraphOperation<string, ResolveProperties, ResolveProperties, OperationType<"resolve", ResolveProperties, ResolveProperties>>[] = [// TODO: Cleanup the `as ResolveProperties`createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: false,allowPending: false,acceptNil: false,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: false,allowPending: false,acceptNil: true,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: false,allowPending: true,acceptNil: false,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: false,allowPending: true,acceptNil: true,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: true,allowPending: false,acceptNil: false,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: true,allowPending: false,acceptNil: true,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: true,allowPending: true,acceptNil: false,} as ResolveProperties),createGraphOperation(ResolveOperationType, {until: undefined,allowErrors: true,allowPending: true,acceptNil: true,} as ResolveProperties),]

Const CONTEXT

CONTEXT: unique symbol = Symbol.for('muster::CONTEXT')

Const CallNodeType

CallNodeType: StatefulNodeType<"call", CallNodeProperties, CallNodeState, CallNodeData> = createNodeType<'call', CallNodeProperties, CallNodeState, CallNodeData>('call', {shape: {target: graphTypes.nodeDefinition,args: types.optional(types.oneOfType([types.arrayOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),types.objectOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),]),),},state: {currentValue: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),},getInitialState() {return {currentValue: pending(),};},operations: {evaluate: {cacheable: false,run(node: CallNode,options: never,dependencies: never,context: never,state: CallNodeState,): GraphNode | NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<CallNodeState, CallNodeData>, node: CallNode): void {const { target } = node.definition.properties;const updateState = ([result]: [GraphNode]) => {this.setState({ currentValue: result });return result;};this.setState({currentValue: resolve([{ target, until: untilSupportsCallOperation }], ([targetNode]) => {const { args } = node.definition.properties;let argNodes: CallArgumentMap | CallArgumentArray | undefined;if (args) {argNodes = isCallArgumentMap(args)? mapValues(args, (arg) => (isGraphNode(arg) ? arg : withScopeFrom(node, arg))): args.map((arg) => (isGraphNode(arg) ? arg : withScopeFrom(node, arg)));}const traverseTarget = traverse(targetNode.definition, callOperation(argNodes));return resolve([{ target: withScopeFrom(targetNode, traverseTarget) }], updateState);}),});},},},})

The implementation of a call node. See the call documentation for more information.

Const CallOperationType

CallOperationType: OperationType<"call", CallProperties> = createOperationType<'call',CallProperties>('call', {cacheable: false,shape: {args: types.optional(types.oneOfType([types.arrayOf(types.oneOfType([graphTypes.graphNode, graphTypes.nodeDefinition])),types.objectOf(types.oneOfType([graphTypes.graphNode, graphTypes.nodeDefinition])),]),),},})

An implementation of the callOperation. See the callOperation documentation to find out more.

Const CatchErrorNodeType

CatchErrorNodeType: StaticNodeType<"catch-error", CatchErrorNodeProperties> = createNodeType<'catch-error', CatchErrorNodeProperties>('catch-error', {deserialize: false,serialize: false,shape: {fallbackGenerator: types.saveHash(types.func),target: graphTypes.nodeDefinition,},})

The implementation of the catchError. See the catchError documentation to learn more.

Const CeilNodeType

CeilNodeType: StatelessNodeType<"ceil", CeilNodeProperties> = createNodeType<'ceil',CeilNodeProperties>('ceil', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: CeilNodeProperties): Array<NodeDependency> {return [{ target, until: untilNumberValueNode(CeilNodeType, 'target') }];},run(node: CeilNode, options: never, [target]: [ValueNode<number>]): NodeDefinition {return toValue(Math.ceil(target.definition.properties.value));},},},})

The implementation of the ceil node. See the ceil documentation to learn more.

Const CharAtNodeType

CharAtNodeType: StatelessNodeType<"char-at", CharAtNodeProperties> = createNodeType<'char-at',CharAtNodeProperties>('char-at', {shape: {index: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ index, subject }: CharAtNodeProperties): Array<NodeDependency> {return [{target: index,until: untilPositiveIntegerValueNode(CharAtNodeType, 'index'),},{target: subject,acceptNil: true,until: untilStringValueNode(CharAtNodeType, 'subject'),},];},run(node: CharAtNode,options: never,[index, subject]: [ValueNode<number>, ValueNode<string>],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const indexValue = index.definition.properties.value;const content = subject.definition.properties.value;if (indexValue >= content.length) return nil();return value(content.charAt(indexValue));},},},})

The implementation of the charAt node. See the charAt documentation to learn more.

Const ChooseNodeType

ChooseNodeType: StatelessNodeType<"choose", ChooseNodeProperties> = createNodeType<'choose',ChooseNodeProperties>('choose', {shape: {options: types.arrayOf(graphTypes.nodeDefinition),fallback: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ options }: ChooseNodeProperties): Array<NodeDependency> {return options.map((option) => ({target: option.properties.pattern,until: untilConditionIsValueNode,}));},run(node: ChooseNode, operation: never, conditions: Array<ValueNode<any>>): NodeDefinition {const { fallback, options } = node.definition.properties;const matchIndex = conditions.findIndex((condition) =>Boolean(condition.definition.properties.value),);if (matchIndex === -1) {return fallback.properties.value;}return options[matchIndex].properties.value;},},},})

The implementation of the choose node. See the choose documentation to learn more.

Const ClampNodeType

ClampNodeType: StatelessNodeType<"clamp", ClampNodeProperties> = createNodeType<'clamp',ClampNodeProperties>('clamp', {shape: {max: graphTypes.nodeDefinition,min: graphTypes.nodeDefinition,value: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ max, min, value }: ClampNodeProperties): Array<NodeDependency> {return [{ target: max, until: untilNumberValueNode(ClampNodeType, 'max') },{ target: min, until: untilNumberValueNode(ClampNodeType, 'min') },{ target: value, until: untilNumberValueNode(ClampNodeType, 'value') },];},run(node: ClampNode,options: never,[max, min, value]: [ValueNode<number>, ValueNode<number>, ValueNode<number>],): NodeDefinition {const maxNumber = max.definition.properties.value;const minNumber = min.definition.properties.value;const valueNumber = value.definition.properties.value;return toValue(Math.min(Math.max(valueNumber, minNumber), maxNumber));},},},})

The implementation of the clamp node. See the clamp documentation to learn more.

Const ClearNodeType

ClearNodeType: StatelessNodeType<"clear", ClearNodeProperties> = createNodeType<'clear',ClearNodeProperties>('clear', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {cacheable: false,getDependencies({ target }: ClearNodeProperties): [NodeDependency] {return [{target,until: untilSupportsClearOperation,},];},run(node: ClearNode,options: never,[target]: [GraphNode, ValueNode<number>],context: never,): GraphAction {return createGraphAction(target, clearOperation());},},},})

The implementation of the clear node. See the clear documentation for more information.

Const ClearOperationType

ClearOperationType: OperationType<"clear", ClearProperties> = createOperationType<'clear',ClearProperties>('clear', {cacheable: false,})

An implementation of the clearOperation. See the clearOperation documentation to find out more.

Const CollectionNodeTypes

CollectionNodeTypes: Array<NodeType> = [...KeysNodeTypes,...TransformsNodeTypes,AddItemAtNodeType,ApplyTransformsNodeType,ArrayNodeType,ArrayListNodeType,ArrayReducerNodeType,ContainsNodeType,HeadNodeType,ItemWithIdNodeType,IterateNodeType,NodeListNodeType,PopNodeType,PushNodeType,ReduceNodeType,RemoveItemNodeType,RemoveItemAtNodeType,RemoveItemsNodeType,ShiftNodeType,TransduceNodeType,UnshiftNodeType,]

Const CombineLatestNodeType

CombineLatestNodeType: StatelessNodeType<"combineLatest", CombineLatestNodeProperties> = createNodeType<'combineLatest', CombineLatestNodeProperties>('combineLatest', {shape: {operations: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {cacheable: false,getDependencies({ operations }: CombineLatestNodeProperties): Array<NodeDependency> {return operations.map((operation) => ({ target: operation }));},run(node: CombineLatestNode, options: never, dependencies: Array<GraphNode>): NodeDefinition {return array(dependencies.map((node) => node.definition));},},},})

The implementation of the combineLatest. See the combineLatest documentation page to lear more.

Const CombinedMiddlewareNodeType

CombinedMiddlewareNodeType: StatelessNodeType<"combined-middleware", CombinedMiddlewareNodeProperties> = createOperationComposer<'combined-middleware',RequestOperation['type']['name'],RequestOperation>('combined-middleware', ['request'])

Const CombinedReducerNodeType

CombinedReducerNodeType: StatelessNodeType<"combinedReducer", CombinedReducerNodeProperties> = createOperationComposer<'combinedReducer',TransformOperation['type']['name'],TransformOperation>('combinedReducer', ['init', 'step', 'result'])

Const ContainsNodeType

ContainsNodeType: StatelessNodeType<"contains", ContainsNodeProperties> = createNodeType<'contains', ContainsNodeProperties>('contains', {shape: {item: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,comparator: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: ContainsNodeProperties): Array<NodeDependency> {return [{target,until: {predicate: supportsContainsOperation,errorMessage(node: GraphNode) {return getInvalidTypeErrorMessage('Target node does not support contains operation',{ received: node.definition },);},},},];},run(node: ContainsNode, operation: never, [target]: [GraphNode]): GraphAction {const { item, comparator } = node.definition.properties;return createGraphAction(target, containsOperation(item, comparator));},},},})

The implementation of the contains. See the contains documentation for more information.

Const ContainsOperationType

ContainsOperationType: OperationType<"contains", ContainsProperties> = createOperationType<'contains', ContainsProperties>('contains', {shape: {item: graphTypes.nodeDefinition,comparator: graphTypes.nodeDefinition,},})

An implementation of the containsOperation. See the containsOperation documentation to find out more.

Const ContextNodeType

ContextNodeType: StatelessNodeType<"context", ContextNodeProperties> = createNodeType<'context',ContextNodeProperties>('context', {shape: {name: types.oneOfType<string | symbol>([types.string, types.symbol]),},operations: {evaluate: {getContextDependencies({ name }: ContextNodeProperties): [ContextDependency] {return [{ name, required: true, until: shallow }];},run(node: ContextNode,options: never,dependencies: Array<never>,[contextNode]: [GraphNode],): GraphNode {return contextNode;},},},})

The implementation of the context node. See the context documentation to learn more.

Const CountNodeType

CountNodeType: StatelessNodeType<"count", CountNodeProperties> = createNodeType('count',{operations: {transformItems: {run(node: CountNode, operation: TransformItemsOperation): NodeDefinition {return nodeList([withScopeFrom(node, value(operation.properties.items.length))]);},},init: {run(node: CountNode): NodeDefinition {const initialState = 0;return value(initialState);},},step: {run(node: CountNode, operation: StepOperation<number>): NodeDefinition {return value(operation.properties.acc + 1);},},result: {run(node: CountNode, operation: ResultOperation<number>): NodeDefinition {const { acc, next } = operation.properties;const finalValue = array([value(acc)]);return next ? value(transduce(finalValue, [next])) : value(finalValue);},},},},)

The implementation of the count node. See the count documentation for more information.

Const CreateBehaviorNodeType

CreateBehaviorNodeType: StatelessNodeType<"createBehavior", CreateBehaviorNodeProperties> = createNodeType<'createBehavior', CreateBehaviorNodeProperties>('createBehavior', {serialize: false,deserialize: false,shape: {operations: types.objectOf(types.saveHash(types.func)),},operations: {[WILDCARD_OPERATION]: {run(node: CreateBehaviorNode, operation: GraphOperation): NodeDefinition {const operationHandler = node.definition.properties.operations[operation.type.name];if (!operationHandler) {return error(getInvalidTypeError(`This createBehavior node does not implement the '${operation.type.name}' operation.`,{expected: Object.keys(node.definition.properties.operations),received: operation.type.name,},),);}return operationHandler(getParams(node.context), operation.properties);},},},})

Implementation of the createBehavior. See the createBehavior documentation for more information.

Const CreateCallerNodeType

CreateCallerNodeType: StaticNodeType<"createCaller", CreateCallerNodeProperties> = createNodeType<'createCaller', CreateCallerNodeProperties>('createCaller', {shape: {key: types.saveHash(types.any),disposeEmitter: types.optional(types.saveHash(types.func)),matcher: types.saveHash(types.func),},})

The implementation of the createCaller. See the createCaller documentation to learn more.

Const CreateSetterNodeType

CreateSetterNodeType: StaticNodeType<"createSetter", CreateSetterNodeProperties> = createNodeType<'createSetter', CreateSetterNodeProperties>('createSetter', {shape: {key: types.saveHash(types.any),disposeEmitter: types.optional(types.saveHash(types.func)),matcher: types.saveHash(types.func),},})

The implementation of the createSetter node. See the createSetter documentation to learn more.

Const DEFAULT

DEFAULT: symbol = Symbol('DEFAULT')

Const DEFAULT_NODE_TYPES

DEFAULT_NODE_TYPES: Array<NodeType> = [...ArithmeticNodeTypes,...BrowserNodeTypes,...CollectionNodeTypes,...GraphNodeTypes,...LogicNodeTypes,...RemoteNodeTypes,...StringNodeTypes,]

Const DebugNodeType

DebugNodeType: StatelessNodeType<"debug", DebugNodeProperties> = createNodeType<'debug',DebugNodeProperties>('debug', {serialize: false,deserialize: false,shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: DebugNodeProperties): [NodeDependency] {return [{target,allowPending: true,allowErrors: true,acceptNil: true,},];},run(node: DebugNode, options: never, [targetValue]: [GraphNode]): NodeDefinition {const { target } = node.definition.properties;const input = target;const resolved = targetValue.definition;window.console.log({ input, resolved });debugger;return target;},},},})

The implementation of the debug. See the debug documentation to learn more.

Const DeferNodeType

DeferNodeType: StaticNodeType<"defer", DeferNodeProperties> = createNodeType<'defer',DeferNodeProperties>('defer', {deserialize: false,serialize: false,shape: {fallbackGenerator: types.saveHash(types.func),target: graphTypes.nodeDefinition,},})

The implementation of the defer. See the defer documentation to learn more.

Const DispatchNodeType

DispatchNodeType: StatelessNodeType<"dispatch", DispatchNodeProperties> = createNodeType<'dispatch', DispatchNodeProperties>('dispatch', {shape: {event: graphTypes.event,},operations: {evaluate: {cacheable: false,run(node: DispatchNode): NodeDefinition {const { event } = node.definition.properties;node.scope.events.emit(event);return ok();},},},})

The implementation of the dispatch. See the dispatch documentation to learn more.

Const DivideNodeType

DivideNodeType: StatelessNodeType<"divide", DivideNodeProperties> = createNodeType<'divide',DivideNodeProperties>('divide', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: DivideNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(DivideNodeType, 'operand'),}));},run(node: DivideNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {assertEnoughOperands(operands);const operandValues = operands.map((operand) => operand.definition.properties.value);return value(operandValues.reduce((total, value) => total / value));},},},})

The implementation of the divide node. See the divide documentation to learn more.

Const DoneNodeType

DoneNodeType: StaticNodeType<"done", DoneNodeProperties> = createNodeType<'done',DoneNodeProperties>('done', {shape: {value: types.optional(types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),),},})

An implementation of the done node. See the done documentation to find out more.

Const EMPTY_CONTEXT_DEPENDENCIES

EMPTY_CONTEXT_DEPENDENCIES: Array<never> = []

Const EMPTY_HASH_SET

EMPTY_HASH_SET: Set<string> = createHashSet()

Const EMPTY_STACK

EMPTY_STACK: Stack<CachedAction> = createStack<CachedAction>()

Const EVENT_RESET_VARIABLE

EVENT_RESET_VARIABLE: "$$event:reset-variable" = "$$event:reset-variable"

Const EmptyItemNodeType

EmptyItemNodeType: StaticNodeType<"empty-item", EmptyItemNodeProperties> = createNodeType<'empty-item', EmptyItemNodeProperties>('empty-item', {shape: {},})

An implementation of the emptyItem node. See the emptyItem documentation to find out more.

Const EndsWithNodeType

EndsWithNodeType: StatelessNodeType<"ends-with", EndsWithNodeProperties> = createNodeType<'ends-with', EndsWithNodeProperties>('ends-with', {shape: {pattern: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ pattern, subject }: EndsWithNodeProperties): Array<NodeDependency> {return [{target: pattern,until: untilStringValueNode(EndsWithNodeType, 'pattern'),},{target: subject,acceptNil: true,until: untilStringValueNode(EndsWithNodeType, 'subject'),},];},run(node: EndsWithNode,options: never,[pattern, subject]: [ValueNode<string>, ValueNode<string>],): NodeDefinition {if (NilNodeType.is(subject)) return value(false);const patternValue = pattern.definition.properties.value;const subjectValue = subject.definition.properties.value;return value((subjectValue || '').endsWith(patternValue));},},},})

The implementation of the endsWith node. See the endsWith documentation to learn more.

Const EntriesNodeType

EntriesNodeType: StaticNodeType<"entries", EntriesNodeProperties> = createNodeType<'entries',EntriesNodeProperties>('entries', {shape: {children: types.optional(graphTypes.nodeDefinition),},})

The implementation of the entries. See the entries documentation to learn more.

Const EqNodeType

EqNodeType: StatelessNodeType<"eq", EqNodeProperties> = createNodeType<'eq',EqNodeProperties>('eq', {shape: {left: graphTypes.nodeDefinition,right: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ left, right }: EqNodeProperties): Array<NodeDependency> {return [left, right].map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Eq node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: EqNode,options: never,[left, right]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const leftValue = left.definition.properties.value;const rightValue = right.definition.properties.value;return value(leftValue === rightValue);},},},})

The implementation of the eq node. See the eq documentation to learn more.

Const ErrorNodeType

ErrorNodeType: StaticNodeType<"error", ErrorNodeProperties, SerializedErrorNodeProperties> = createNodeType<'error', ErrorNodeProperties, SerializedErrorNodeProperties>('error', {shape: {error: types.shape({message: types.string,stack: types.ignore,}),code: types.optional(types.string),data: types.optional(types.saveHash(types.any)),path: types.optional(types.saveHash(types.arrayOf(types.any))),remotePath: types.optional(types.saveHash(types.arrayOf(types.any))),},serialize(properties: ErrorNodeProperties): SerializedErrorNodeProperties {const { error, code, data, path, remotePath } = properties;return {error: error instanceof Error ? { message: error.message, stack: error.stack } : error,code,data,path,remotePath,};},deserialize(data: SerializedErrorNodeProperties): ErrorNodeProperties {const safeData = data || {};const error = safeData.error || new Error('Unknown error');return {error,code: safeData.code,data: safeData.data,path: safeData.path,remotePath: safeData.remotePath,};},})

The implementation of the error node. See the error documentation to learn more.

Const EvaluateOperationType

EvaluateOperationType: OperationType<"evaluate"> = createOperationType<'evaluate'>('evaluate',)

An implementation of the evaluateOperation. See the evaluateOperation documentation to find out more.

Const ExtendNodeType

ExtendNodeType: StatelessNodeType<"extend", ExtendNodeProperties> = createNodeType<'extend',ExtendNodeProperties>('extend', {shape: {nodes: types.arrayOf(graphTypes.nodeDefinition),},operations: {getChild: {run(node: ExtendNode, operation: GetChildOperation): NodeDefinition {return resolveChildNode(node, node.definition.properties.nodes, operation.properties.key);},},},})

The implementation of the extend. See the extend documentation to learn more.

Const ExternalStatefulNodeType

ExternalStatefulNodeType: StatefulNodeType<"stateful", ExternalStatefulNodeProperties<any>, ExternalStatefulNodeState> = createNodeType<'stateful', ExternalStatefulNodeProperties<any>, ExternalStatefulNodeState>('stateful',{state: {currentValue: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),},shape: {valueStream: types.saveHash(types.any),},getInitialState(): ExternalStatefulNodeState {return {currentValue: pending(),};},serialize: false,deserialize: false,operations: {evaluate: {run(node: ExternalStatefulNode<any>,options: never,dependencies: Array<never>,context: Array<never>,state: ExternalStatefulNodeState,): NodeDefinition | GraphNode {return state.currentValue;},onSubscribe(this: NodeExecutionContext<ExternalStatefulNodeState, ExternalStatefulNodeData>,node: ExternalStatefulNode<any>,): void {const subscription = node.definition.properties.valueStream.subscribe((v) => {this.setState((s) => ({...s,currentValue: isGraphNode(v) ? v : toValue(v),}));});this.setData({subscription,});},onUnsubscribe(this: NodeExecutionContext<ExternalStatefulNodeState, ExternalStatefulNodeData>,): void {const subscription = this.getData().subscription;subscription && subscription.unsubscribe();},},},},)

The implementation of the stateful node. See the stateful documentation to learn more.

Const FACTORY

FACTORY: unique symbol = Symbol('HASH_FACTORY')

Const FLUSH

FLUSH: "$$event:flush" = "$$event:flush"

Const FactoryNodeType

FactoryNodeType: StatefulNodeType<"factory", FactoryNodeProperties, FactoryNodeState, FactoryNodeData> = createNodeType<'factory', FactoryNodeProperties, FactoryNodeState, FactoryNodeData>('factory', {state: {instance: graphTypes.nodeDefinition,},serialize: false,deserialize: false,shape: {factory: types.saveHash(types.func),},getInitialState(): FactoryNodeState {return {instance: pending(),};},operations: {evaluate: {run(node: FactoryNode,options: never,dependencies: Array<never>,contextDependencies: Array<never>,state: FactoryNodeState,): NodeDefinition {const { instance } = state;return instance;},onSubscribe(this: NodeExecutionContext<FactoryNodeState, FactoryNodeData>,node: FactoryNode,): void {const { factory } = node.definition.properties;this.setState({instance: factory(),});},onInvalidate(this: NodeExecutionContext<FactoryNodeState, FactoryNodeData>,node: FactoryNode,): void {const { factory } = node.definition.properties;this.setState({instance: factory(),});},onUnsubscribe(this: NodeExecutionContext<FactoryNodeState, FactoryNodeData>,node: FactoryNode,): void {this.setState({instance: pending(),});},},},})

The implementation of the factory. See the factory documentation to learn more.

Const FetchItemsNodeType

FetchItemsNodeType: StaticNodeType<"fetch-items", FetchItemsNodeProperties> = createNodeType<'fetch-items', FetchItemsNodeProperties>('fetch-items', {shape: {target: graphTypes.nodeDefinition,},operations: {getItems: {getDependencies({ target }: FetchItemsNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsGetItemOperation,},];},run(node: FetchItemsNode, operation: GetItemsOperation, [target]: [GraphNode]) {if (NilNodeType.is(target)) return target;const { transforms } = operation.properties;return resolve([{ target: traverse(target, getItemsOperation()), until: untilPlaceholderOrItems }],([items]: [GraphNode]) => {if (NilNodeType.is(items)) return items;if (!PlaceholderNodeType.is(items)) {return createGraphAction(items, getItemsOperation(transforms));}return applyTransforms(withScopeFrom(items, nodeList([items])) as NodeListNode,transforms,);},);},},},})

An implementation of the fetchItems node. See the fetchItems documentation to find out more.

Const FieldsNodeType

FieldsNodeType: StaticNodeType<"fields", FieldsNodeProperties, SerializedFieldsNodeProperties> = createNodeType<'fields', FieldsNodeProperties, SerializedFieldsNodeProperties>('fields', {shape: {fields: types.objectOf(graphTypes.nodeDefinition),},serialize<T>({ fields }: FieldsNodeProperties,serialize: (node: NodeDefinition) => T,): SerializedFieldsNodeProperties<T> {return {fields: mapValues(fields, (field) => serialize(field)),};},deserialize<T>({ fields }: SerializedFieldsNodeProperties<T>,deserialize: (node: T) => NodeDefinition,): FieldsNodeProperties {return {fields: mapValues(fields, (field) => deserialize(field)),};},})

The implementation of the fields node. See the fields documentation to learn more.

Const FilterNodeType

FilterNodeType: StatelessNodeType<"filter", FilterNodeProperties> = createNodeType('filter',{shape: {predicate: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ predicate }: FilterNodeProperties,operation: TransformItemsOperation,): Array<NodeDependency> {return operation.properties.items.map((item) => ({target: apply([item], predicate),until: untilIsValueNode,}));},run(node: FilterNode,operation: TransformItemsOperation,filterResults: Array<ValueNode<any>>,): NodeDefinition {const { items } = operation.properties;const filterValues = filterResults.map((result) => result.definition.properties.value);return nodeList((zip<GraphNode | ValueNode<any>>(items, filterValues) as Array<[GraphNode, ValueNode<any>]>).filter(([item, filterValue]) => Boolean(filterValue)).map(([item]) => item),);},},init: {run(node: FilterNode, operation: InitOperation): NodeDefinition | GraphAction {const { next } = operation.properties;if (!next) {return error('Filter reducer cannot be used as a base reducer');}return createGraphAction(next, init());},},step: {getDependencies({ predicate }: FilterNodeProperties,operation: StepOperation<any>,): [NodeDependency] {return [{target: apply([operation.properties.item], predicate),until: untilIsValueNode,},];},run(node: FilterNode,operation: StepOperation<any>,[result]: [ValueNode<any>],): NodeDefinition | GraphAction {const { acc, item, next } = operation.properties;if (!next) {return error('Filter reducer cannot be used as a base reducer');}const { value: resultValue } = result.definition.properties;return resultValue ? createGraphAction(next, step(acc, item)) : value(acc);},},result: {run(node: FilterNode, operation: ResultOperation<any>): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('Filter reducer cannot be used as a base reducer');}return createGraphAction(next, result(acc));},},},},)

The implementation of the filter node. See the filter documentation to learn more.

Const FirstItemNodeType

FirstItemNodeType: StatelessNodeType<"firstItem", FirstItemNodeProperties> = createNodeType('firstItem', {operations: {transformItems: {run(node: FirstItemNode, operation: TransformItemsOperation): NodeDefinition {return nodeList(operation.properties.items.slice(0, 1));},},init: {run(node: FirstItemNode, operation: InitOperation): NodeDefinition | GraphAction {const { next } = operation.properties;return next ? createGraphAction(next, init()) : value(undefined);},},step: {run(node: FirstItemNode, operation: StepOperation<any>): NodeDefinition {const { acc, item, next } = operation.properties;return done(next ? traverse(next, step(acc, item)) : value(item));},},result: {run(node: FirstItemNode, operation: ResultOperation<any>): NodeDefinition | GraphAction {const { acc, next } = operation.properties;return next ? createGraphAction(next, result(acc)) : value(nodeList(acc ? [acc] : []));},},},})

The implementation of the firstItem node. See the firstItem documentation to learn more.

Const FirstNodeType

FirstNodeType: StaticNodeType<"first"> = createNodeType<'first'>('first')

An implementation of the first node. See the first documentation to find out more.

Const FloorNodeType

FloorNodeType: StatelessNodeType<"floor", FloorNodeProperties> = createNodeType<'floor',FloorNodeProperties>('floor', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: FloorNodeProperties): Array<NodeDependency> {return [{ target, until: untilNumberValueNode(FloorNodeType, 'target') }];},run(node: FloorNode, options: never, [target]: [ValueNode<number>]): NodeDefinition {return toValue(Math.floor(target.definition.properties.value));},},},})

The implementation of the floor node. See the floor documentation to learn more.

Const FlowNodeType

FlowNodeType: StatelessNodeType<"flow", FlowNodeProperties> = createNodeType<'flow',FlowNodeProperties>('flow', {shape: {functions: types.arrayOf(graphTypes.nodeDefinition),},operations: {call: {run(node: FlowNode, operation: CallOperation) {return composeApplyNodes(node.definition.properties.functions, operation.properties.args);},},},})

The implementation of the flow node. See the flow documentation for more information.

Const FnNodeType

FnNodeType: StatelessNodeType<"fn", FnNodeProperties> = createNodeType<'fn',FnNodeProperties>('fn', {shape: {argIds: types.arrayOf(types.string),body: graphTypes.nodeDefinition,hasNamedArgs: types.bool,},operations: {call: {run(node: FnNode, operation: CallOperation): NodeDefinition | GraphNode {const { argIds, body, hasNamedArgs } = node.definition.properties;const { args } = operation.properties;if (hasNamedArgs) {// Handle calling function with named argumentsif (args && isCallArgumentArray(args)) {return error('An fn() expected to have been called with named arguments, ' +'but was called with an array of arguments.',);}const receivedArgsNames = args ? Object.keys(args) : [];const isMissingArguments = argIds.some((name) => !receivedArgsNames.includes(name));if (isMissingArguments) {return error(getInvalidTypeError('An fn() was called with unexpected number of arguments.', {expected: argIds,received: receivedArgsNames,}),);}const sanitizedArgs = fromPairs(toPairs(args).map(([name, value]) => [`$$named-arg:${name}`,isGraphNode(value) ? value : withScopeFrom(node, value),]),);const childContext = createContext(node.context, sanitizedArgs);return createGraphNode(node.scope, childContext, body);}// Handle calling function with an array of argumentsif (args && isCallArgumentMap(args)) {return error('An fn() expected to have been called with an array of arguments, ' +'but was called with named arguments.',);}if ((!args && argIds.length > 0) || (args && args.length < argIds.length)) {return error(getInvalidTypeError('Too few arguments applied to fn.', {expected: argIds.length,received: args ? args.length : 0,}),);}const trimmedArgs = (args ? args.slice(0, argIds.length) : []).map((arg) =>isGraphNode(arg) ? arg : withScopeFrom(node, arg),);const context = fromPairs(zip<string | GraphNode>(argIds, trimmedArgs) as Array<[string, GraphNode]>);const childContext = createContext(node.context, context);return createGraphNode(node.scope, childContext, body);},},},})

The implementation of the fn. See the fn documentation to learn more.

Const FormatNodeType

FormatNodeType: StatelessNodeType<"format", FormatNodeProperties> = createNodeType<'format',FormatNodeProperties>('format', {shape: {format: types.string,data: types.arrayOf(types.arrayOf(types.oneOfType<string | NodeDefinition>([types.string, graphTypes.nodeDefinition]),),),},operations: {evaluate: {getDependencies({ data }: FormatNodeProperties): Array<NodeDependency> {return data.map(([key, dependency]) => ({target: dependency,until: untilStringValueNode(FormatNodeType, `data.${key}`),}));},run(node: FormatNode,options: never,dependencies: Array<ValueNode<string>>,): NodeDefinition {const data = buildFormatInput(node.definition.properties.data, dependencies);return value(es6TemplateStrings(node.definition.properties.format, data));},},},})

The implementation of the format node. See the format documentation to learn more.

Const FromBase64NodeType

FromBase64NodeType: StatelessNodeType<"from-base64", FromBase64NodeProperties> = createNodeType<'from-base64', FromBase64NodeProperties>('from-base64', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: FromBase64NodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(FromBase64NodeType, 'subject'),},];},run(node: FromBase64Node, options: never, [subject]: [ValueNode<string>]): NodeDefinition {if (NilNodeType.is(subject)) return nil();return value(atob(subject.definition.properties.value));},},},})

The implementation of the fromBase64 node. See the fromBase64 documentation to learn more.

Const FromPromiseNodeType

FromPromiseNodeType: StatefulNodeType<"fromPromise", FromPromiseNodeProperties, FromPromiseNodeState> = createNodeType<'fromPromise', FromPromiseNodeProperties, FromPromiseNodeState>('fromPromise', {serialize: false,deserialize: false,state: {currentValue: types.optional(graphTypes.nodeDefinition),pendingUpdate: types.optional(types.saveHash(types.any)),updateError: types.optional(graphTypes.nodeDefinition),},shape: {get: types.optional(types.saveHash(types.func)),set: types.optional(types.saveHash(types.func)),},getInitialState(): FromPromiseNodeState {return {currentValue: undefined,pendingUpdate: undefined,updateError: undefined,};},operations: {evaluate: {run(node: FromPromiseNode,options: never,dependencies: Array<never>,context: Array<never>,state: FromPromiseNodeState,): NodeDefinition {const { get } = node.definition.properties;if (!get) {return error('Specified fromPromise node is write-only');}const { currentValue } = state;return currentValue || pending();},onInvalidate(this: NodeExecutionContext<FromPromiseNodeState, FromPromiseNodeData>,node: FromPromiseNode,): void {this.setState((state) => ({...state,currentValue: undefined,pendingUpdate: undefined,updateError: undefined,}));fetchValue(this, node);},onSubscribe(this: NodeExecutionContext<FromPromiseNodeState, FromPromiseNodeData>,node: FromPromiseNode,): void {this.setData((data) => ({...data,isSubscribed: true,}));fetchValue(this, node);},onUnsubscribe(this: NodeExecutionContext<FromPromiseNodeState, FromPromiseNodeData>): void {this.setData((data) => ({...data,isSubscribed: false,}));},},set: {run(node: FromPromiseNode,options: never,dependencies: Array<never>,context: Array<never>,state: FromPromiseNodeState,): NodeDefinition {const { set } = node.definition.properties;if (!set) {return error('Specified fromPromise node is read-only');}return state.pendingUpdate ? pending() : state.updateError || ok();},onSubscribe(this: NodeExecutionContext<FromPromiseNodeState, FromPromiseNodeData>,node: FromPromiseNode,operation: SetOperation,): void {const { set } = node.definition.properties;if (!set) return;const { value: newValue } = operation.properties;const { currentValue: previousValue } = this.getState();if (!previousValue) {this.retain();}this.setData((data) => ({...data,pendingGet: undefined,}));const pendingUpdate = Promise.resolve(set(getParams(node.context), valueOf(newValue))).catch((e) => error(e)).then((result) => {if (this.getState().pendingUpdate !== pendingUpdate) return result;this.setState((state) => ({...state,currentValue: isOkNodeDefinition(result) ? newValue : state.currentValue,pendingUpdate: undefined,updateError: isErrorNodeDefinition(result) ? result : undefined,}));return result;});this.setState((state) => ({...state,pendingUpdate,updateError: undefined,}));},},reset: {run(): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<FromPromiseNodeState, FromPromiseNodeData>,node: FromPromiseNode,) {const { currentValue: previousValue } = this.getState();if (previousValue) {this.release();}this.setState((state) => ({...state,currentValue: undefined,pendingUpdate: undefined,}));const { isSubscribed } = this.getData();if (isSubscribed) {fetchValue(this, node);}},},},})

Implementation of the fromPromise. See the fromPromise documentation for more information.

Const FromStreamMiddlewareNodeType

FromStreamMiddlewareNodeType: StatelessNodeType<"from-stream-middleware", FromStreamMiddlewareNodeProperties> = createNodeType<'from-stream-middleware', FromStreamMiddlewareNodeProperties>('from-stream-middleware',{shape: {streamFactory: types.saveHash(types.func),},operations: {request: {run(node: FromStreamMiddlewareNode, operation: RequestOperation): NodeDefinition {const responseStream = node.definition.properties.streamFactory(operation.properties.query,);return fromStream(responseStream);},},},},)

Const FromStreamNodeType

FromStreamNodeType: StatefulNodeType<"fromStream", FromStreamNodeProperties, FromStreamNodeState> = createNodeType<'fromStream', FromStreamNodeProperties, FromStreamNodeState>('fromStream', {serialize: false,deserialize: false,state: {currentValue: types.optional(graphTypes.nodeDefinition),},shape: {factory: types.saveHash(types.oneOfType<Function | { subscribe: Function }>([types.func,types.instance({ subscribe: types.func }),types.shape({ subscribe: types.func }),]),),},getInitialState(): FromStreamNodeState {return {currentValue: undefined,};},operations: {evaluate: {run(node: FromStreamNode,options: never,dependencies: Array<never>,context: Array<never>,state: FromStreamNodeState,): NodeDefinition {const { currentValue } = state;return currentValue || pending();},onSubscribe(this: NodeExecutionContext<FromStreamNodeState, FromStreamNodeData>,node: FromStreamNode,): void {const { factory } = node.definition.properties;const { subscription: existingSubscription } = this.getData();let isSync = true;let syncValue: NodeDefinition | undefined;const stream = typeof factory === 'function' ? factory(getParams(node.context)) : factory;const subscription = stream.subscribe((rawValue) => {const valueNode = isNodeDefinition(rawValue) ? rawValue : value(rawValue);if (isSync) {syncValue = valueNode;} else {this.setState({currentValue: valueNode,});}});isSync = false;if (existingSubscription) {existingSubscription.unsubscribe();}this.setData({subscription,});if (syncValue) {this.setState({currentValue: syncValue,});}},onUnsubscribe(this: NodeExecutionContext<FromStreamNodeState, FromStreamNodeData>): void {const { subscription } = this.getData();subscription && subscription.unsubscribe();},},},})

The implementation of the fromStream node. See the fromStream documentation to learn more.

Const FuzzyTraverseNodeType

FuzzyTraverseNodeType: StatelessNodeType<"fuzzyTraverse", FuzzyTraverseNodeProperties> = createNodeType<'fuzzyTraverse', FuzzyTraverseNodeProperties>('fuzzyTraverse', {serialize: false,deserialize: false,shape: {operation: graphTypes.graphOperation,target: types.oneOfType([graphTypes.graphNode, graphTypes.nodeDefinition]),},operations: {evaluate: {getDependencies({ operation, target }: FuzzyTraverseNodeProperties): Array<NodeDependency> {return [{target,until: {predicate(node: GraphNode) {return supportsOperationType(operation.type.name, node.definition);},errorMessage(node: GraphNode) {return getInvalidTypeErrorMessage(`Node does not support ${operation.type.name} operation`,{expected: `Node supporting ${operation.type.name} operation`,received: node.definition,},);},},},];},run(node: FuzzyTraverseNode, operation: never, [target]: Array<never>): GraphAction {return createGraphAction(target, node.definition.properties.operation);},},},})

The implementation of the fuzzyTraverse. See the fuzzyTraverse documentation to learn more.

Const GRAPH_ACTION

GRAPH_ACTION: unique symbol = Symbol.for('muster::GRAPH_ACTION')

Const GRAPH_NODE

GRAPH_NODE: unique symbol = Symbol.for('muster::GRAPH_NODE')

Const GRAPH_OPERATION

GRAPH_OPERATION: unique symbol = Symbol.for('muster::GRAPH_OPERATION')

Const GetChildOperationType

GetChildOperationType: OperationType<"getChild", GetChildProperties> = createOperationType<'getChild', GetChildProperties>('getChild', {shape: {key: types.optional(types.saveHash(types.any)),},})

An implementation of the getChildOperation. See the getChildOperation documentation to find out more.

Const GetItemsOperationType

GetItemsOperationType: OperationType<"getItems", GetItemsProperties> = createOperationType<'getItems', GetItemsProperties>('getItems', {shape: {transforms: types.arrayOf(types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),),},})

An implementation of the getItemsOperation. See the getItemsOperation documentation to find out more.

Const GetLengthNodeType

GetLengthNodeType: StatelessNodeType<"get-length", GetLengthNodeProperties> = createNodeType<'get-length', GetLengthNodeProperties>('get-length', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: GetLengthNodeProperties) {return [{target,until: {predicate: supportsLengthOperation,errorMessage(node: GraphNode) {return getInvalidTypeErrorMessage('Target node does not support length operation', {received: node.definition,});},},},];},run(node: GetLengthNode, operation: never, [target]: [GraphNode]): GraphAction {return createGraphAction(target, lengthOperation());},},},})

An implementation of the length node used to compute a length of a target node. See the length documentation to find out more.

Const GetNodeType

GetNodeType: StatelessNodeType<"get", GetNodeProperties> = createNodeType<'get',GetNodeProperties>('get', {shape: {subject: graphTypes.nodeDefinition,key: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject, key }: GetNodeProperties): Array<NodeDependency> {return [{target: subject,until: untilNodeSupportedByGet,},{target: key,until: untilIsValueNodeOrKeyNode,},];},run(node: GetNode,operation: never,[subjectNode, keyNode]: [GraphNode, ValueNode<any> | ListKeyNode],): NodeDefinition | GraphNode | GraphAction {if (isListKeyNode(keyNode)) {if (FirstNodeType.is(keyNode)) {return withScopeFrom(subjectNode,head(applyTransforms(subjectNode.definition, [firstItem()])),);}if (LastNodeType.is(keyNode)) {return withScopeFrom(subjectNode,head(applyTransforms(subjectNode.definition, [lastItem()])),);}if (NthNodeType.is(keyNode)) {const { index } = keyNode.definition.properties;return withScopeFrom(subjectNode,head(applyTransforms(subjectNode.definition, [nthItem(index)])),);}if (LengthNodeType.is(keyNode)) {if (supportsLengthOperation(subjectNode)) {return withScopeFrom(subjectNode, length(subjectNode.definition));}return withScopeFrom(subjectNode,head(applyTransforms(subjectNode.definition, [count()])),);}}if (!supportsGetChildOperation(subjectNode)) {return withScopeFrom(subjectNode,error(untilNodeSupportedByGet.errorMessage(subjectNode)),);}return createGraphAction(subjectNode,getChildOperation(keyNode.definition.properties.value),);},},},})

The implementation of the get. See the get documentation page for more information.

Const GraphNodeNodeType

GraphNodeNodeType: StatelessNodeType<"graphNode", GraphNodeNodeProperties> = createNodeType<'graphNode', GraphNodeNodeProperties>('graphNode', {deserialize: false,serialize: false,shape: {value: graphTypes.graphNode,},operations: {evaluate: {run(node: GraphNodeNode): GraphNode {return node.definition.properties.value;},},},})

The implementation of the graphNode. See the graphNode documentation to learn more.

Const GraphNodeTypes

GraphNodeTypes: Array<NodeType> = [ActionNodeType,ApplyNodeType,CallNodeType,CatchErrorNodeType,CombineLatestNodeType,ContextNodeType,CreateCallerNodeType,CreateSetterNodeType,CreateBehaviorNodeType,DebugNodeType,DeferNodeType,DispatchNodeType,DoneNodeType,EntriesNodeType,ErrorNodeType,ExtendNodeType,FactoryNodeType,FieldsNodeType,ExternalStatefulNodeType,FlowNodeType,FnNodeType,FromPromiseNodeType,FromStreamNodeType,GetNodeType,GraphNodeNodeType,IfErrorNodeType,IfPendingNodeType,InvalidateNodeType,InvalidateOnNodeType,IsNilNodeType,IsPendingNodeType,IsUpdatingNodeType,IteratorResultNodeType,KeyNodeType,LegacyQueryNodeType,LogNodeType,NilNodeType,OkNodeType,OnNodeType,OnceNodeType,OptimisticNodeType,ParallelNodeType,ParamNodeType,ParentNodeType,InjectDependenciesNodeType,PartialNodeType,PendingNodeType,PlaceholderNodeType,PropertyNodeType,QueryNodeType,QuerySetNodeType,QuerySetCallOperationNodeType,QuerySetGetChildOperationNodeType,QuerySetGetItemsOperationNodeType,QuerySetOperationNodeType,QuerySetResultNodeType,QuerySetSetOperationNodeType,ResetNodeType,ResolveNodeType,RootNodeType,ScopeNodeType,SeriesNodeType,SetNodeType,SetResultNodeType,TakeLastNodeType,TraverseNodeType,TreeNodeType,UpdateNodeType,ValueNodeType,VariableNodeType,WithContextNodeType,WithScopeNodeType,WithTransformsNodeType,]

Const GroupByNodeType

GroupByNodeType: StatelessNodeType<"group-by", GroupByNodeProperties> = createNodeType('group-by',{shape: {predicate: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ predicate }: GroupByNodeProperties,operation: TransformItemsOperation,): Array<NodeDependency> {return operation.properties.items.map((item) => ({target: apply([item], predicate),until: untilIsValueNode,}));},run(node: GroupByNode,operation: TransformItemsOperation,groupByResults: Array<ValueNode<any>>,): NodeDefinition {const { items } = operation.properties;const groupedItems: Map<any, Array<GraphNode>> = new Map();items.forEach((item, index) => {const key = groupByResults[index].definition.properties.value;const items = groupedItems.get(key);if (items) items.push(item);else groupedItems.set(key, [item]);});return nodeList([...groupedItems.entries()].map(([key, items]) => withScopeFrom(node, nodeList(items))),);},},init: {run(node: GroupByNode): NodeDefinition {const initialState = [] as Array<GraphNode>;return value(initialState);},},step: {run(node: GroupByNode, operation: StepOperation<Array<GraphNode>>): NodeDefinition {const { acc, item } = operation.properties;return value([...acc, item]);},},result: {getDependencies({ predicate }: GroupByNodeProperties): Array<NodeDependency> {return [{target: predicate,until: untilSupportsCallOperation,},];},run(node: GroupByNode,operation: ResultOperation<Array<GraphNode>>,[predicate]: [GraphNode],): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('group-by reducer cannot be used as a base reducer');}const sortedItems = resolve(acc.map((item) => ({target: apply([item], predicate.definition),until: untilIsValueNode,})),(groupByResults: Array<ValueNode<any>>) => {const groupedItems: Map<any, Array<GraphNode>> = new Map();acc.forEach((item, index) => {const key = groupByResults[index].definition.properties.value;const items = groupedItems.get(key);if (items) items.push(item);else groupedItems.set(key, [item]);});return nodeList([...groupedItems.entries()].map(([key, items]) =>withScopeFrom(node, nodeList(items)),),);},);return value(transduce(sortedItems, [next]));},},},},)

The implementation of the groupBy. See the groupBy documentation to learn more.

Const GtNodeType

GtNodeType: StatelessNodeType<"gt", GtNodeProperties> = createNodeType<'gt',GtNodeProperties>('gt', {shape: {left: graphTypes.nodeDefinition,right: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ left, right }: GtNodeProperties): Array<NodeDependency> {return [left, right].map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Gt node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: GtNode,options: never,[left, right]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const leftValue = left.definition.properties.value;const rightValue = right.definition.properties.value;return value(leftValue > rightValue);},},},})

The implementation of the gt node. See the gt documentation to learn more.

Const GteNodeType

GteNodeType: StatelessNodeType<"gte", GteNodeProperties> = createNodeType<'gte',GteNodeProperties>('gte', {shape: {left: graphTypes.nodeDefinition,right: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ left, right }: GteNodeProperties): Array<NodeDependency> {return [left, right].map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Gte node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: GteNode,options: never,[left, right]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const leftValue = left.definition.properties.value;const rightValue = right.definition.properties.value;return value(leftValue >= rightValue);},},},})

The implementation of the gte node. See the gte documentation to learn more.

Const HeadNodeType

HeadNodeType: StatelessNodeType<"head", HeadNodeProperties> = createNodeType<'head',HeadNodeProperties>('head', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: HeadNodeProperties): Array<NodeDependency> {return [{target,until: untilValidTargetNode,},];},run(node: HeadNode,options: never,[targetNode]: [NodeListNode | IterableGraphNode | PlaceholderNode | ItemPlaceholderNode],): GraphNode | NodeDefinition {if (NilNodeType.is(targetNode) ||ItemPlaceholderNodeType.is(targetNode) ||PlaceholderNodeType.is(targetNode)) {return targetNode;}if (NodeListNodeType.is(targetNode)) {const { items } = targetNode.definition.properties;return items.length > 0 ? items[0] : nil();}if (supportsIterateOperation(node)) {return getNextIteratorResult(targetNode, resolveIteratorResult);}// the item must support get items operation thenreturn withScopeFrom(targetNode,resolve([{target: traverse(targetNode, getItemsOperation()),until: untilValidGetItemsResult,},],([itemsNode]: [NodeListNode]) => {if (NilNodeType.is(itemsNode) ||ItemPlaceholderNodeType.is(itemsNode) ||PlaceholderNodeType.is(itemsNode)) {return itemsNode;}const { items } = itemsNode.definition.properties;return items.length > 0 ? items[0] : nil();},),);},},},})

The implementation of the head node. See the head documentation to learn more.

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"arrayReducer", ArrayReducerNodeProperties, ArrayReducerNodeProperties, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(ArrayReducerNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StaticNodeType<"first", object, object>> = createNodeDefinition(FirstNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"count", CountNodeProperties, CountNodeProperties, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(CountNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"identity", IdentityNodeProperties, IdentityNodeProperties, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(IdentityNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"root", object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(RootNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"nil", object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(NilNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"lastItem", LastItemNodeProperties, LastItemNodeProperties, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(LastItemNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StaticNodeType<"pending", object, object>> = createNodeDefinition(PendingNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StaticNodeType<"last", object, object>> = createNodeDefinition(LastNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"firstItem", FirstItemNodeProperties, FirstItemNodeProperties, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(FirstItemNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StaticNodeType<"length", object, object>> = createNodeDefinition(LengthNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StaticNodeType<"ok", object, object>> = createNodeDefinition(OkNodeType, {})

Const INSTANCE

INSTANCE: StaticNodeDefinition<string, object, object, StatelessNodeType<"parent", object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>>> = createNodeDefinition(ParentNodeType, {})

Const ITEM_ID_CONTEXT

ITEM_ID_CONTEXT: "$$array:item-id" = "$$array:item-id"

Const ITEM_ID_KEY

ITEM_ID_KEY: "$$item-with-id:id" = "$$item-with-id:id"

Const IdentityNodeType

IdentityNodeType: StatelessNodeType<"identity", IdentityNodeProperties> = createNodeType<'identity', IdentityNodeProperties>('identity', {shape: {},operations: {call: {run(node: IdentityNode, operation: CallOperation): GraphNode | NodeDefinition {const { args } = operation.properties;if (!args) return nil();if (isCallArgumentArray(args)) return args[0];const argsNames = Object.keys(args);return args[argsNames[0]];},},},})

The implementation of the identity. See the identity documentation to learn more.

Const IdentityOperationType

IdentityOperationType: OperationType<"identity"> = createOperationType<'identity'>('identity',)

An implementation of the identityOperation. See the identityOperation documentation to find out more.

Const IfElseNodeType

IfElseNodeType: StatelessNodeType<"ifElse", IfElseNodeProperties> = createNodeType<'ifElse',IfElseNodeProperties>('ifElse', {shape: {if: graphTypes.nodeDefinition,then: graphTypes.nodeDefinition,else: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ if: ifNode }: IfElseNodeProperties): Array<NodeDependency> {return [{target: ifNode,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('IfElse node condition must resolve to value() nodes',{expected: ValueNodeType,received: node.definition,},);},},},];},run(node: IfElseNode, options: never, [condition]: [ValueNode<any>]): NodeDefinition {const { then: thenNode, else: elseNode } = node.definition.properties;const conditionValue = condition.definition.properties.value;return conditionValue ? thenNode : elseNode;},},},})

The implementation of the ifElse node. See the ifElse documentation to learn more.

Const IfErrorNodeType

IfErrorNodeType: StatefulNodeType<"ifError", IfErrorNodeProperties, IfErrorNodeState, IfErrorNodeData> = createNodeType<'ifError', IfErrorNodeProperties, IfErrorNodeState, IfErrorNodeData>('ifError', {state: {previousValues: types.shape({evaluate: types.optional(graphTypes.graphNode),}),},shape: {target: graphTypes.nodeDefinition,fallback: types.saveHash(types.func),},getInitialState(): IfErrorNodeState {return {previousValues: {evaluate: undefined,},};},operations: {evaluate: {getDependencies({ target }: IfErrorNodeProperties): Array<NodeDependency> {return [{target,allowErrors: true,},];},run(node: IfErrorNode,options: never,[target]: [GraphNode],context: Array<never>,state: IfErrorNodeState,): NodeDefinition | GraphNode {const { fallback } = node.definition.properties;const { previousValues } = state;if (ErrorNodeType.is(target)) {const previousValue = previousValues.evaluate;return fallback(target.definition, previousValue && previousValue.definition);}return target;},onUpdate(this: NodeExecutionContext<IfErrorNodeState, IfErrorNodeData>,node: IfErrorNode,options: never,[target]: [GraphNode],): void {if (!ErrorNodeType.is(target)) {this.setState((prevState) => ({previousValues: {...prevState.previousValues,evaluate: target,},}));}},},call: {run(node: IfErrorNode, operation: CallOperation): NodeDefinition | GraphNode {const { fallback, target } = node.definition.properties;return resolve([{ target: traverse(target, operation), allowErrors: true }], ([result]) => {if (ErrorNodeType.is(result)) {return withScopeFrom(node, fallback(result.definition, undefined));}return result;});},},},})

The implementation of the ifError. See the ifError documentation to learn more.

Const IfPendingNodeType

IfPendingNodeType: StatelessNodeType<"ifPending", IfPendingNodeProperties> = createNodeType<'ifPending', IfPendingNodeProperties>('ifPending', {shape: {target: graphTypes.nodeDefinition,fallback: types.oneOfType([types.saveHash(types.func),graphTypes.nodeDefinition,types.saveHash(types.any),]),},operations: {evaluate: {run(node: IfPendingNode) {const { fallback, target } = node.definition.properties;const fallbackGenerator = parseFallbackGenerator(fallback);const queryBuilder = new QueryBuilder(uniqueId('if-pending_'));let resolveMirrorQuery: NodeDefinition = ok();let lastQuerySnapshot: QueriesSnapshot | undefined = undefined;let lastResolvedResult: QuerySetResultNodeDefinition | undefined = undefined;return takeLast([onGlobalEvent(FLUSH)(() => {if (!queryBuilder.isModified) return resolveMirrorQuery;queryBuilder.resetModifiedState();const queryBuilderSnapshot = getQueryBuilderSnapshot(queryBuilder);if (lastQuerySnapshot && isEqual(lastQuerySnapshot, queryBuilderSnapshot)) {return resolveMirrorQuery;}lastQuerySnapshot = queryBuilderSnapshot;const querySetWithCallback = buildQuerySetFromQueryBuilderSnapshot(queryBuilderSnapshot,queryBuilder,);const querySetChildren = querySetWithCallback.node.properties.children;const querySetWithTarget = querySet(target, querySetChildren);return (resolveMirrorQuery = resolve([{target: withScopeFrom(node, querySetWithTarget),until: untilIsArrayNodeOrPendingNode,acceptNil: true,allowPending: true,},],([result]: [ArrayNode | PendingNode]) => {if (!PendingNodeType.is(result)) {// Looks like the query is fully resolved - call the placeholder callbackslastResolvedResult = querySetResult(querySetChildren, result.definition);querySetWithCallback.callback(result.definition);return ok();}// Generate the fallback response and then resolve it to a simpler valuereturn resolve([{target: fallbackGenerator(lastResolvedResult),acceptNil: true,},],([fallback]: [GraphNode]) => {// Check if the fallback was resolved to a query set node// This should simplify things a bitif (lastResolvedResult &&fallback.definition.id === lastResolvedResult.properties.result.id) {querySetWithCallback.callback((fallback as QuerySetResultNode).definition.properties.result,);return ok();}// Otherwise - run the querySet against the fallback to generate a correct resultreturn resolve([{target: withScopeFrom(fallback,querySet(fallback.definition, querySetChildren),),acceptNil: true,allowErrors: true,allowPending: true,},],([fallbackResult]: [GraphNode]) => {querySetWithCallback.callback(fallbackResult.definition);return ok();},);},);},));}),placeholder(queryBuilder, []),]);},},},})

The implementation of the ifPending. See the ifPending documentation to learn more.

Const IncludesNodeType

IncludesNodeType: StatelessNodeType<"includes", IncludesNodeProperties> = createNodeType<'includes', IncludesNodeProperties>('includes', {shape: {pattern: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ pattern, subject }: IncludesNodeProperties): Array<NodeDependency> {return [{target: pattern,until: untilStringValueNode(IncludesNodeType, 'pattern'),},{target: subject,acceptNil: true,until: untilStringValueNode(IncludesNodeType, 'subject'),},];},run(node: IncludesNode,options: never,[pattern, subject]: [ValueNode<string>, ValueNode<string>],): NodeDefinition {if (NilNodeType.is(subject)) return value(false);const patternValue = pattern.definition.properties.value;const subjectValue = subject.definition.properties.value;return value((subjectValue || '').includes(patternValue));},},},})

The implementation of the includes node. See the includes documentation to learn more.

Const InitOperationType

InitOperationType: OperationType<"init", InitProperties> = createOperationType<'init',InitProperties>('init', {shape: {next: types.optional(graphTypes.graphNode),},})

An implementation of the [[initOperation]]. See the [[initOperation]] documentation to find out more.

Const InjectDependenciesNodeType

InjectDependenciesNodeType: StatelessNodeType<"inject-dependencies", InjectDependenciesNodeProperties<NodeDefinition>> = createNodeType('inject-dependencies', {shape: {context: types.optional(types.objectOf(graphTypes.nodeDefinition)),dependencies: types.arrayOf(types.optional(types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),),),target: graphTypes.nodeDefinition,},serialize: false,deserialize: false,operations: {evaluate: {cacheable: true,getDependencies<T extends NodeDefinition>(properties: InjectDependenciesNodeProperties<T>,operation: EvaluateOperation,): Array<Dependency> {const { target } = properties;if (!supportsEvaluateOperation(target)) {return [];}const evaluateOperationHandler = target.type.operations.evaluate;return getDependencies(properties, evaluateOperationHandler, operation);},getContextDependencies<T extends NodeDefinition>(properties: InjectDependenciesNodeProperties<T>,operation: EvaluateOperation,): Array<ContextDependency> {const { target } = properties;if (!supportsEvaluateOperation(target)) {return [];}const evaluateOperationHandler = target.type.operations.evaluate;return getContextDependencies(properties, evaluateOperationHandler, operation);},run<T extends NodeDefinition>(node: InjectDependenciesNode<T>,operation: EvaluateOperation,dependencies: Array<GraphNode>,contextDependencies: Array<GraphNode>,): GraphNode | GraphAction {const { target, context } = node.definition.properties;if (!supportsEvaluateOperation(target)) {return withScopeFrom(node, target);}const nodeType = target.type;const {dependencies: resolvedDependencies,contextDependencies: resolvedContextDependencies,} = getResolvedDependencies(node.definition,nodeType.operations.evaluate,operation,dependencies,contextDependencies,);const targetContext = context? createContext(node.context, mapValues(context, (value) => withScopeFrom(node, value))): node.context;const targetNode = createGraphNode(node.scope, targetContext, target);if (isStatefulNodeType(nodeType)) {return nodeType.operations.evaluate.run(targetNode,evaluateOperation(),resolvedDependencies,resolvedContextDependencies,node.scope.store.getNodeState(targetNode as StatefulGraphNode),);}return nodeType.operations.evaluate.run(targetNode,evaluateOperation(),resolvedDependencies,resolvedContextDependencies,undefined,);},},},})

An implementation of the injectDependencies node. See the injectDependencies documentation to find out more.

Const InvalidateNodeType

InvalidateNodeType: StatefulNodeType<"invalidate", InvalidateNodeProperties> = createNodeType<'invalidate', InvalidateNodeProperties>('invalidate', {state: {},shape: {target: graphTypes.nodeDefinition,},getInitialState(): InvalidateNodeState {return {};},operations: {evaluate: {cacheable: false,run(): GraphNode | NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<InvalidateNodeState, InvalidateNodeData>,node: InvalidateNode,): void {if (!isDynamicNode(node)) {return;}const { target } = node.definition.properties;// Invalidate the target node via the store if it is already subscribedconst wasSubscribed = node.scope.store.invalidate(withScopeFrom(node, target));if (wasSubscribed) {return;}if (!supportsEvaluateOperation(target)) {return;}// The target node is not currently subscribed, so create a temporary subscription to the// target just in order to figure out the next result in the chain, and invalidate thatlet isSync = true;let isCompleted = false;const unsubscribe = node.scope.store.subscribe(withScopeFrom(node,resolve([createGraphAction(withScopeFrom(node, target), evaluateOperation())],([nextTarget]) => withScopeFrom(nextTarget, invalidate(nextTarget.definition)),),),resolveOperation(),() => {isCompleted = true;if (isSync) return;unsubscribe();},);isSync = false;if (isCompleted) {unsubscribe();}},},},})

The implementation of the invalidate. See the invalidate documentation to learn more.

Const InvalidateOnNodeType

InvalidateOnNodeType: StatefulNodeType<"invalidate-on", InvalidateOnNodeProperties, InvalidateOnNodeState> = createNodeType<'invalidate-on', InvalidateOnNodeProperties, InvalidateOnNodeState>('invalidate-on',{state: {},shape: {target: graphTypes.nodeDefinition,predicate: types.saveHash(types.func),},getInitialState(): InvalidateOnNodeState {return {};},operations: {evaluate: {run(node: InvalidateOnNode): NodeDefinition {const { target } = node.definition.properties;return target;},onSubscribe(node: InvalidateOnNode) {const { predicate, target } = node.definition.properties;const { subscription: disposeSubscription } = this.getData();disposeSubscription && disposeSubscription();const subscription = node.scope.events.listen((event) => {if (!predicate(event)) return;const targetNode = withScopeFrom(node, target);node.scope.store.invalidate(targetNode);});this.setData({subscription,});},onUnsubscribe() {const { subscription: disposeSubscription } = this.getData();disposeSubscription && disposeSubscription();},},},},)

The implementation of the invalidateOn. See the invalidateOn to learn more.

Const IsNilNodeType

IsNilNodeType: StatelessNodeType<"is-nil", IsNilNodeProperties> = createNodeType<'is-nil',IsNilNodeProperties>('is-nil', {serialize: false,deserialize: false,shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: IsNilNodeProperties): [NodeDependency] {return [{target,acceptNil: true,},];},run(node: IsNilNode, options: never, [targetValue]: [GraphNode]): NodeDefinition {return value(NilNodeType.is(targetValue));},},},})

The implementation of the isNil. See the isNil documentation to learn more.

Const IsPendingNodeType

IsPendingNodeType: StaticNodeType<"isPending", IsPendingNodeProperties> = createNodeType<'isPending', IsPendingNodeProperties>('isPending', {shape: {target: graphTypes.nodeDefinition,},})

The implementation of the isPending node. See the isPending documentation page to learn more.

Const IsPendingOperationType

IsPendingOperationType: OperationType<"isPending"> = createOperationType<'isPending'>('isPending',)

An implementation of the isPendingOperation. See the isPendingOperation documentation to find out more.

Const IsUpdatingNodeType

IsUpdatingNodeType: StatelessNodeType<"isUpdating", IsUpdatingNodeProperties> = createNodeType<'isUpdating', IsUpdatingNodeProperties>('isUpdating', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: IsUpdatingNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsIsUpdatingOperationOrStaticNode,},];},run(node: IsUpdatingNode,operation: never,[target]: [GraphNode],): NodeDefinition | GraphAction {if (!supportsIsUpdatingOperation(target)) {return value(true);}return createGraphAction(target, isUpdatingOperation());},},},})

The implementation of the isUpdating node. See the isUpdating documentation to learn more.

Const IsUpdatingOperationType

IsUpdatingOperationType: OperationType<"isUpdating"> = createOperationType<'isUpdating'>('isUpdating')

An implementation of the isUpdatingOperation. See the isUpdatingOperation documentation to find out more.

Const ItemIdNodeType

ItemIdNodeType: StaticNodeType<"item-id", ItemIdNodeProperties> = createNodeType<'item-id',ItemIdNodeProperties>('item-id', {shape: {id: types.string,},})

Const ItemPlaceholderNodeType

ItemPlaceholderNodeType: StatelessNodeType<"item-placeholder", ItemPlaceholderNodeProperties> = createNodeType<'item-placeholder', ItemPlaceholderNodeProperties>('item-placeholder', {shape: {results: types.arrayOf(types.shape({node: graphTypes.nodeDefinition,pathPart: types.shape({id: types.string,operation: graphTypes.graphOperation,}),}),),isEmpty: types.bool,path: types.arrayOf(types.shape({id: types.string,operation: graphTypes.graphOperation,}),),queryBuilder: types.saveHash(types.any),},operations: {[WILDCARD_OPERATION]: {getDependencies({ path, queryBuilder }: ItemPlaceholderNodeProperties,operation: GraphOperation,): Array<NodeDependency> {return [{target: traverse(placeholder(queryBuilder, path), operation),allowPending: true,until: untilValidPlaceholderResult,},];},run(node: ItemPlaceholderNode,operation: GraphOperation,[placeholder]: [PlaceholderNode],): NodeDefinition | GraphNode {const { results } = node.definition.properties;const matchingResult = results.find((result) => result.pathPart.id === operation.id);if (!matchingResult) return placeholder;return isSetOperation(operation) && isOkNodeDefinition(matchingResult.node)? operation.properties.value: matchingResult.node;},},},})

An implementation of the itemPlaceholder node. See the itemPlaceholder documentation to find out more.

Const ItemWithIdNodeType

ItemWithIdNodeType: StatelessNodeType<"item-with-id", ItemWithIdNodeProperties> = createNodeType<'item-with-id', ItemWithIdNodeProperties>('item-with-id', {shape: {id: types.string,item: graphTypes.nodeDefinition,},operations: {evaluate: {run(node: ItemWithIdNode): GraphNode {const { id, item } = node.definition.properties;return createGraphNode(node.scope,createContext(node.context, {[ITEM_ID_KEY]: withScopeFrom(node, value(id)),}),item,);},},},})

The implementation of the itemWithId node. See the itemWithId documentation to find out more.

Const IterateNodeType

IterateNodeType: StatelessNodeType<"iterate", IterateNodeProperties> = createNodeType<'iterate',IterateNodeProperties>('iterate', {shape: {target: graphTypes.nodeDefinition,transforms: types.arrayOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),},operations: {evaluate: {getDependencies({ target, transforms }: IterateNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsIterateOperation,},...transforms.map((transformer) => ({target: transformer,until: untilSupportsStepOperation,})),];},run(node: IterateNode,options: never,[targetNode, ...transforms]: Array<GraphNode>,): NodeDefinition | GraphNode {return withScopeFrom(targetNode,transduce(targetNode.definition, [...transforms, arrayReducer()]),);},},},})

Const IterateOperationType

IterateOperationType: OperationType<"iterate"> = createOperationType<'iterate'>('iterate',)

An implementation of the iterateOperation. See the iterateOperation documentation to find out more.

Const IteratorResultNodeType

IteratorResultNodeType: StaticNodeType<"iteratorResult", IteratorResultNodeProperties> = createNodeType<'iteratorResult', IteratorResultNodeProperties>('iteratorResult', {shape: {value: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),next: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),},})

An implementation of the iteratorResult node. See the iteratorResult documentation to find out more.

Const JoinNodeType

JoinNodeType: StatelessNodeType<"join", JoinNodeProperties> = createNodeType<'join',JoinNodeProperties>('join', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),separator: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ operands, separator }: JoinNodeProperties): Array<NodeDependency> {return [{target: separator,until: untilValidSeparator,},...operands.map((operand) => ({target: operand,acceptNil: true,until: untilValidJoinOperand,})),];},run(node: JoinNode,options: never,[separator, ...operands]: [ValueNode<string>, ValueNode<string | Array<string>>],): NodeDefinition {return value(flatMap(operands.filter((operand) => !NilNodeType.is(operand)), (operand) => {const { value } = operand.definition.properties;return typeof value === 'string' ? [value] : value;}).join(separator.definition.properties.value),);},},},})

The implementation of the join node. See the join documentation to learn more.

Const KeyNodeType

KeyNodeType: StaticNodeType<"key", KeyNodeProperties> = createNodeType<'key',KeyNodeProperties>('key', {shape: {key: graphTypes.nodeDefinition,children: types.optional(graphTypes.nodeDefinition),},})

The implementation of the key node. See the key documentation to learn more.

Const KeysNodeTypes

KeysNodeTypes: Array<NodeType> = [FirstNodeType,GetLengthNodeType,LastNodeType,LengthNodeType,NthNodeType,]

Const LOCATION_CHANGED

LOCATION_CHANGED: "$$event:location-changed" = "$$event:location-changed"

Const LOCATION_PART_CHANGED

LOCATION_PART_CHANGED: "$$event:location-part-changed" = "$$event:location-part-changed"

Const LastItemNodeType

LastItemNodeType: StatelessNodeType<"lastItem", LastItemNodeProperties> = createNodeType('lastItem', {operations: {transformItems: {run(node: LastItemNode, operation: TransformItemsOperation): NodeDefinition {return nodeList(operation.properties.items.slice(-1));},},init: {run(node: LastItemNode): NodeDefinition {return value(undefined);},},step: {run(node: LastItemNode, operation: StepOperation<any>): NodeDefinition {return value(operation.properties.item);},},result: {run(node: LastItemNode, operation: ResultOperation<any>): NodeDefinition {const { acc, next } = operation.properties;const finalValue = nodeList(acc ? [acc] : []);return next ? value(transduce(finalValue, [next])) : value(finalValue);},},},})

The implementation of the lastItem node. See the lastItem documentation to learn more.

Const LastNodeType

LastNodeType: StaticNodeType<"last"> = createNodeType<'last'>('last')

An implementation of the last node. See the last documentation to find out more.

Const LegacyQueryNodeType

LegacyQueryNodeType: StatelessNodeType<"legacyQuery", LegacyQueryNodeProperties> = createNodeType<'legacyQuery', LegacyQueryNodeProperties>('legacyQuery', {shape: {keys: graphTypes.nodeDefinition,root: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ keys }: LegacyQueryNodeProperties): [NodeDependency] {return [{target: keys,until: untilIsFieldsNodeOrCollectionFieldsNode,},];},run(node: LegacyQueryNode,operation: never,[keys]: [FieldsNode | EntriesNode | WithTransformsNode],): NodeDefinition | GraphNode {const { root } = node.definition.properties;if (FieldsNodeType.is(keys)) {if (supportsGetChildOperation(root)) {return resolveFields(withScopeFrom(node, root), keys);}return resolve([{target: root,until: untilSupportsGetChildOperation,},],([rootNode]) => resolveFields(rootNode, keys),);}if (isCollectionFieldsNode(keys)) {if (supportsGetItemsOperation(root)) {return resolveList(withScopeFrom(node, root), keys);}return resolve([{target: root,until: untilSupportsGetItemsOperation,},],([rootNode]) => resolveList(rootNode, keys),);}return error(getInvalidTypeError('Invalid query definition.', {expected: [FieldsNodeType, EntriesNodeType, WithTransformsNodeType],received: keys,}),);},},},})

The implementation of the legacyQuery node. See the legacyQuery documentation to learn more.

Const LengthNodeType

LengthNodeType: StaticNodeType<"length"> = createNodeType<'length'>('length')

An implementation of the length node used as part of a ref node. See the length documentation to find out more.

Const LengthOperationType

LengthOperationType: OperationType<"length", LengthProperties> = createOperationType<'length',LengthProperties>('length', {cacheable: false,shape: {},})

An implementation of the lengthOperation. See the lengthOperation documentation to find out more.

Const LocationDataNodeType

LocationDataNodeType: StatefulNodeType<"locationData", LocationDataNodeProperties, LocationDataNodeState> = createNodeType<'locationData', LocationDataNodeProperties, LocationDataNodeState>('locationData',{state: {currentValue: graphTypes.nodeDefinition,},shape: {history: types.shape({id: types.string,}),paramsEncoder: types.optional(types.shape({encode: types.saveHash(types.func),decode: types.saveHash(types.func),}),),update: types.optional(types.bool),},getInitialState(properties: LocationDataNodeProperties): LocationDataNodeState {return {currentValue: computeCurrentValue(properties.history.location, properties.paramsEncoder),};},operations: {evaluate: {run(node: LocationDataNode,options: never,dependencies: Array<never>,context: Array<never>,state: LocationDataNodeState,): NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<LocationDataNodeState, LocationDataNodeData>,node: LocationDataNode,): void {if (this.getData().disposeEventListener) return;const { history, paramsEncoder } = node.definition.properties;this.setData({disposeEventListener: node.scope.events.listen((event) => {if (event.type !== LOCATION_CHANGED) return;this.setState({currentValue: computeCurrentValue(history.location, paramsEncoder),});}),disposeHistoryListener: history.listen((location) => {this.setState({currentValue: computeCurrentValue(location, paramsEncoder),});}),});},onUnsubscribe(this: NodeExecutionContext<LocationDataNodeState, LocationDataNodeData>,): void {const { disposeEventListener, disposeHistoryListener } = this.getData();disposeEventListener && disposeEventListener();disposeHistoryListener && disposeHistoryListener();},},set: {run(): NodeDefinition {return series([dispatch(LOCATION_PART_CHANGED), ok()]);},onSubscribe(this: NodeExecutionContext<LocationDataNodeState, LocationDataNodeData>,node: LocationDataNode,operation: SetOperation,): void {const { history } = node.definition.properties;const paramsValue = operation.properties.value.properties.value;getHistoryUpdater(history, node.definition.properties.update)({...history.location,search: paramsToSearch(paramsValue, node.definition.properties.paramsEncoder),});this.setState({currentValue: value(paramsValue),});},},},},)

Const LocationNodeType

LocationNodeType: StatefulNodeType<"location", LocationNodeProperties, LocationNodeState> = createNodeType<'location', LocationNodeProperties, LocationNodeState>('location', {state: {currentValue: graphTypes.nodeDefinition,history: types.shape({id: types.string,}),},shape: {hash: types.optional(types.string),paramsEncoder: types.optional(types.shape({encode: types.saveHash(types.func),decode: types.saveHash(types.func),}),),update: types.optional(types.bool),},getInitialState(properties: LocationNodeProperties): LocationNodeState {const history = (properties.hash? createHashHistory({ hashType: properties.hash }): createBrowserHistory()) as HistoryWithId;history.id = uniqueId('history_');return {currentValue: computeCurrentValue(history.location, properties.paramsEncoder),history,};},operations: {evaluate: {run(node: LocationNode,options: never,dependencies: Array<never>,context: Array<never>,state: LocationNodeState,): NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<LocationNodeState, LocationNodeData>,node: LocationNode,): void {if (this.getData().unsubscribeHistory) return;const { history } = this.getState();const { paramsEncoder } = node.definition.properties;this.setData({unsubscribeEvent: node.scope.events.listen((event) => {if (event.type !== LOCATION_PART_CHANGED) return;this.setState((state) => ({...state,currentValue: computeCurrentValue(history.location, paramsEncoder),}));}),unsubscribeHistory: history.listen((location) => {this.setState((state) => ({...state,currentValue: computeCurrentValue(location, paramsEncoder),}));}),});},onUnsubscribe(this: NodeExecutionContext<LocationNodeState, LocationNodeData>): void {const { unsubscribeEvent, unsubscribeHistory } = this.getData();unsubscribeEvent && unsubscribeEvent();unsubscribeHistory && unsubscribeHistory();},},getChild: {run(node: LocationNode,operation: GetChildOperation,dependencies: Array<never>,context: Array<never>,state: LocationNodeState,): NodeDefinition | GraphNode {const { key } = operation.properties;const { history } = state;const childContext = createChildPathContext(node, key);if (key === 'path') {return createGraphNode(node.scope, childContext, locationPath(history));}if (key === 'params') {const { paramsEncoder, update } = node.definition.properties;return createGraphNode(node.scope,childContext,locationData(history, paramsEncoder, update),);}return nil();},},set: {run(node: LocationNode,options: never,dependencies: Array<never>,context: Array<never>,state: LocationNodeState,): NodeDefinition {return series([dispatch(LOCATION_CHANGED), ok()]);},onSubscribe(this: NodeExecutionContext<LocationNodeState, LocationNodeData>,node: LocationNode,operation: SetOperation,): void {const { history } = this.getState();const value = operation.properties.value.properties.value;const { paramsEncoder } = node.definition.properties;getHistoryUpdater(history, node.definition.properties.update)({pathname: value.path,search: paramsToSearch(value.params, paramsEncoder),});this.setState((state) => ({...state,currentValue: computeCurrentValue(history.location, paramsEncoder),}));},},},})

The implementation of the location node. See the location documentation to learn more.

Const LocationPathNodeType

LocationPathNodeType: StatefulNodeType<"locationPath", LocationPathNodeProperties, LocationPathNodeState> = createNodeType<'locationPath', LocationPathNodeProperties, LocationPathNodeState>('locationPath',{state: {currentValue: graphTypes.nodeDefinition,},shape: {history: types.shape({id: types.string,}),update: types.optional(types.bool),},getInitialState(properties: LocationPathNodeProperties): LocationPathNodeState {return {currentValue: value(properties.history.location.pathname),};},operations: {evaluate: {run(node: LocationPathNode,options: never,dependencies: Array<never>,context: Array<never>,state: LocationPathNodeState,): NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<LocationPathNodeState, LocationPathNodeData>,node: LocationPathNode,): void {if (this.getData().disposeEventListener) return;const { history } = node.definition.properties;this.setData({disposeEventListener: node.scope.events.listen((event) => {if (event.type !== LOCATION_CHANGED) return;this.setState({currentValue: value(history.location.pathname),});}),disposeHistoryListener: history.listen((location) => {this.setState((state) => ({...state,currentValue: value(location.pathname),}));}),});},onUnsubscribe(this: NodeExecutionContext<LocationPathNodeState, LocationPathNodeData>,): void {const { disposeEventListener, disposeHistoryListener } = this.getData();disposeEventListener && disposeEventListener();disposeHistoryListener && disposeHistoryListener();},},set: {run(): NodeDefinition {return series([dispatch(LOCATION_PART_CHANGED), ok()]);},onSubscribe(this: NodeExecutionContext<LocationPathNodeState, LocationPathNodeData>,node: LocationPathNode,operation: SetOperation,): void {const { history } = node.definition.properties;const pathValue = operation.properties.value.properties.value;getHistoryUpdater(history, node.definition.properties.update)({...history.location,pathname: pathValue,});this.setState({currentValue: value(pathValue),});},},},},)

Const LogMiddlewareNodeType

LogMiddlewareNodeType: StatelessNodeType<"log-middleware", LogMiddlewareNodeProperties> = createNodeType<'log-middleware', LogMiddlewareNodeProperties>('log-middleware', {shape: {logRequests: types.bool,logResponses: types.bool,sink: types.saveHash(types.func),},operations: {request: {run(node: LogMiddlewareNode, operation: RequestOperation): NodeDefinition {const { logRequests, logResponses, sink } = node.definition.properties;const { metadata, next, query } = operation.properties;if (!next) {return error('LogMiddleware cannot be used as a base middleware.');}if (logRequests) {sink(`Request [${operation.id}]:`, getType(operation.properties.query));}return resolve([{target: withScopeFrom(next,traverse(next.definition, requestOperation(query, metadata)),),allowErrors: true,},],([response]) => {if (logResponses) {sink(`Response [${operation.id}]:`, getType(response.definition));}return response;},);},},},})

Const LogNodeType

LogNodeType: StatelessNodeType<"log", LogNodeProperties> = createNodeType<'log',LogNodeProperties>('log', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: LogNodeProperties): [NodeDependency] {return [{target,allowPending: true,allowErrors: true,acceptNil: true,},];},run(node: LogNode, options: never, [targetValue]: [GraphNode]): NodeDefinition {const { target } = node.definition.properties;const input = target;const output = targetValue.definition;window.console.log({ input: getType(input), output: getType(output) });return target;},},},})

The implementation of the log. See the log documentation to learn more.

Const LogicNodeTypes

LogicNodeTypes: Array<NodeType> = [AndNodeType,ChooseNodeType,EqNodeType,GtNodeType,GteNodeType,IfElseNodeType,LtNodeType,LteNodeType,NotNodeType,OrNodeType,OtherwiseNodeType,SwitchOnNodeType,WhenNodeType,]

Const LowerCaseNodeType

LowerCaseNodeType: StatelessNodeType<"lower-case", LowerCaseNodeProperties> = createNodeType<'lower-case', LowerCaseNodeProperties>('lower-case', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: LowerCaseNodeProperties): Array<NodeDependency> {return [{target: subject,until: untilStringValueNode(LowerCaseNodeType, 'subject'),},];},run(node: LowerCaseNode, options: never, [subject]: [ValueNode<string>]): NodeDefinition {return value(subject.definition.properties.value.toLowerCase());},},},})

The implementation of the lowerCase node. See the lowerCase documentation to learn more.

Const LtNodeType

LtNodeType: StatelessNodeType<"lt", LtNodeProperties> = createNodeType<'lt',LtNodeProperties>('lt', {shape: {left: graphTypes.nodeDefinition,right: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ left, right }: LtNodeProperties): Array<NodeDependency> {return [left, right].map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Lt node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: LtNode,options: never,[left, right]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const leftValue = left.definition.properties.value;const rightValue = right.definition.properties.value;return value(leftValue < rightValue);},},},})

The implementation of the lt node. See the lt documentation to learn more.

Const LteNodeType

LteNodeType: StatelessNodeType<"lte", LteNodeProperties> = createNodeType<'lte',LteNodeProperties>('lte', {shape: {left: graphTypes.nodeDefinition,right: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ left, right }: LteNodeProperties): Array<NodeDependency> {return [left, right].map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Lte node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: LteNode,options: never,[left, right]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const leftValue = left.definition.properties.value;const rightValue = right.definition.properties.value;return value(leftValue <= rightValue);},},},})

The implementation of the lte node. See the lte documentation to learn more.

Const MATCHER

MATCHER: unique symbol = Symbol.for('muster::MATCHER')

Const MATCHERS

MATCHERS: object

Type declaration

  • [id: string]: object

Const MAX_OPERATION_COUNT

MAX_OPERATION_COUNT: 9999999 = 9999999

Const MAX_STACK_SIZE

MAX_STACK_SIZE: 512 = 512

Const MISSING_PARAM_NAME

MISSING_PARAM_NAME: "$$graph-missing" = "$$graph-missing"

Const MapNodeType

MapNodeType: StatelessNodeType<"map", MapNodeProperties> = createNodeType('map', {shape: {transform: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ transform }: MapNodeProperties,operation: TransformItemsOperation,): Array<NodeDependency> {return operation.properties.items.map((item) => {const transformItem = fuzzyTraverse(transform, callOperation([item]));return resolveShallow(transformItem);});},run(node: MapNode,operation: TransformItemsOperation,items: Array<GraphNode>,): NodeDefinition {return nodeList(items);},},init: {run(node: MapNode, operation: InitOperation): NodeDefinition | GraphAction {const { next } = operation.properties;if (!next) {return error('Map reducer cannot be used as a base reducer');}return createGraphAction(next, init());},},step: {run(node: MapNode, operation: StepOperation<any>): NodeDefinition | GraphAction {const { acc, item, next } = operation.properties;if (!next) {return error('Map reducer cannot be used as a base reducer');}const { transform } = node.definition.properties;const transformedItem = apply([item], transform);return createGraphAction(next, step(acc, withScopeFrom(node, transformedItem)));},},result: {run(node: MapNode, operation: ResultOperation<any>): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('Map reducer cannot be used as a base reducer');}return createGraphAction(next, result(acc));},},},})

The implementation of the map node. See the map documentation to learn more.

Const MatchPatternNodeType

MatchPatternNodeType: StatelessNodeType<"match-pattern", MatchPatternNodeProperties> = createNodeType<'match-pattern', MatchPatternNodeProperties>('match-pattern', {shape: {regex: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ regex, subject }: MatchPatternNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(MatchPatternNodeType, 'subject'),},{target: regex,until: untilRegexNode(MatchPatternNodeType, 'regex'),},];},run(node: MatchPatternNode,options: never,[subject, regex]: [ValueNode<string>, RegexNode],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const pattern = regex.definition.properties.pattern;const result = subjectValue.match(pattern);return result ? array(result.map(value)) : nil();},},},})

The implementation of the matchPattern node. See the matchPattern documentation to learn more.

Const MaxNodeType

MaxNodeType: StatelessNodeType<"max", MaxNodeProperties> = createNodeType<'max',MaxNodeProperties>('max', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: MaxNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(MaxNodeType, 'operand'),}));},run(node: MaxNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {if (operands.length === 0) {return value(0);}return value(Math.max(...operands.map((operand) => operand.definition.properties.value)));},},},})

The implementation of the max node. See the max documentation to learn more.

Const MinNodeType

MinNodeType: StatelessNodeType<"min", MinNodeProperties> = createNodeType<'min',MinNodeProperties>('min', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: MinNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(MinNodeType, 'operand'),}));},run(node: MinNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {if (operands.length === 0) {return value(0);}return value(Math.min(...operands.map((operand) => operand.definition.properties.value)));},},},})

The implementation of the min node. See the min documentation to learn more.

Const MockResponseMiddlewareNodeType

MockResponseMiddlewareNodeType: StatelessNodeType<"mock-response-middleware", MockResponseMiddlewareNodeProperties> = createNodeType('mock-response-middleware', {shape: {responseFactory: types.saveHash(types.func),},operations: {request: {run(node: MockResponseMiddlewareNode, operation: RequestOperation): NodeDefinition {return node.definition.properties.responseFactory(operation.properties.query);},},},})

Const ModNodeType

ModNodeType: StatelessNodeType<"mod", ModNodeProperties> = createNodeType<'mod',ModNodeProperties>('mod', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: ModNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(ModNodeType, 'operand'),}));},run(node: ModNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {assertEnoughOperands(operands);const operandValues = operands.map((operand) => operand.definition.properties.value);return value(operandValues.reduce((total, value) => total % value));},},},})

The implementation of the mod node. See the mod documentation to learn more.

Const MultiplyNodeType

MultiplyNodeType: StatelessNodeType<"multiply", MultiplyNodeProperties> = createNodeType<'multiply', MultiplyNodeProperties>('multiply', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: MultiplyNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(MultiplyNodeType, 'operand'),}));},run(node: MultiplyNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {const operandValues = operands.map((operand) => operand.definition.properties.value);return value(operandValues.reduce((total, value) => total * value, 1));},},},})

The implementation of the multiply node. See the multiply documentation to learn more.

Const NODE_DEFINITION

NODE_DEFINITION: unique symbol = Symbol.for('muster::NODE_DEFINITION')

Const NODE_MAP_MATCHER

NODE_MAP_MATCHER: Matcher<object, Matcher<NodeDefinition<any, any, any, object, any, StaticNodeType<any, any, any> | StatelessNodeType<any, any, any, string, GraphOperation<string, object, object, OperationType<string, object, object>>> | StatefulNodeType<any, any, any, object, any, string, GraphOperation<string, object, object, OperationType<string, object, object>>>>, any>> = types.objectOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.proxiedNode]),)

Const NODE_TYPE

NODE_TYPE: unique symbol = Symbol.for('muster::NODE_TYPE')

Const NOT_FOUND

NOT_FOUND: "NOT_FOUND" = "NOT_FOUND"

Const NilNodeType

NilNodeType: StatelessNodeType<"nil"> = createNodeType<'nil'>('nil', {operations: {evaluate: {run(): NodeDefinition {return value(undefined);},},[WILDCARD_OPERATION]: {run(node: NilNode): GraphNode {return node;},},},})

The implementation of the nil. See the nil documentation to learn more.

Const NodeListNodeType

NodeListNodeType: StatelessNodeType<"nodeList", NodeListNodeProperties> = createNodeType<'nodeList', NodeListNodeProperties>('nodeList', {shape: {items: types.arrayOf(graphTypes.graphNode),},operations: {getItems: {getDependencies(properties: NodeListNodeProperties,operation: GetItemsOperation,): Array<NodeDependency> {const { transforms } = operation.properties;return transforms.length === 0? []: [{target: transforms[0],until: untilSupportsTransformItemsOperation,},];},run(node: NodeListNode,operation: GetItemsOperation,[firstTransform]: [GraphNode],): NodeDefinition | GraphNode {const { items } = node.definition.properties;const { transforms } = operation.properties;if (transforms.length === 0) {return node;}const remainingTransforms = transforms.slice(1);return resolve([{target: traverse(firstTransform, transformItems(items)),until: untilSupportsGetItemsOperation,},],([transformedItems]: [ListGraphNode]) =>remainingTransforms.length === 0? transformedItems: createGraphAction(transformedItems, getItemsOperation(remainingTransforms)),);},},iterate: {run(node: NodeListNode): NodeDefinition {const { items } = node.definition.properties;if (items.length === 0) {return nil();}return iteratorResult(items[0], nodeList(items.slice(1)));},},length: {run(node: NodeListNode): NodeDefinition {return value(node.definition.properties.items.length);},},},})

An implementation of the nodeList node. See the nodeList documentation to find out more.

Const NotNodeType

NotNodeType: StatelessNodeType<"not", NotNodeProperties> = createNodeType<'not',NotNodeProperties>('not', {shape: {condition: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ condition }: NotNodeProperties): Array<NodeDependency> {return [{target: condition,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Not node condition must resolve to a value() node',{expected: ValueNodeType,received: node.definition,},);},},},];},run(node: NotNode, options: never, [condition]: [ValueNode<any>]): NodeDefinition {return value(!condition.definition.properties.value);},},},})

The implementation of the not node. See the not documentation to learn more.

Const NthItemNodeType

NthItemNodeType: StatelessNodeType<"nthItem", NthItemNodeProperties> = createNodeType('nthItem',{shape: {index: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ index }: NthItemNodeProperties): Array<NodeDependency> {return [{target: index,until: untilIsPositiveIntegerValueNode,},];},run(node: NthItemNode,operation: TransformItemsOperation,[index]: [ValueNode<number>],): NodeDefinition {const { value: indexValue } = index.definition.properties;return nodeList(operation.properties.items.slice(indexValue, indexValue + 1));},},init: {run(node: NthItemNode): NodeDefinition {return value(0);},},step: {getDependencies({ index }: NthItemNodeProperties): Array<NodeDependency> {return [{target: index,until: untilIsPositiveIntegerValueNode,},];},run(node: NthItemNode,operation: StepOperation<number>,[target]: [ValueNode<number>],): NodeDefinition {const { acc, item } = operation.properties;const { value: targetIndex } = target.definition.properties;const currentIndex = acc;if (currentIndex === targetIndex) {return done(value(item));}return value(currentIndex + 1);},},result: {run(node: NthItemNode, operation: ResultOperation<number | GraphNode>): NodeDefinition {const { acc, next } = operation.properties;const finalValue = nodeList(isGraphNode(acc) ? [acc] : []);return next ? value(transduce(finalValue, [next])) : value(finalValue);},},},},)

The implementation of the nthItem node. See the nthItem documentation to learn more.

Const NthNodeType

NthNodeType: StaticNodeType<"nth", NthNodeProperties> = createNodeType<'nth',NthNodeProperties>('nth', {shape: {index: types.number,},})

An implementation of the nth node. See the nth documentation to find out more.

Const OPERATION_TYPE

OPERATION_TYPE: unique symbol = Symbol.for('muster::OPERATION_TYPE')

Const OkNodeType

OkNodeType: StaticNodeType<"ok"> = createNodeType<'ok'>('ok')

The implementation of the ok node. See the ok documentation to learn more.

Const OnGlobalEventDebouncedNodeType

OnGlobalEventDebouncedNodeType: StatefulNodeType<"on-global-event-debounced", OnGlobalEventDebouncedNodeProperties, OnGlobalEventDebouncedState, OnGlobalEventDebouncedData> = createNodeType<'on-global-event-debounced',OnGlobalEventDebouncedNodeProperties,OnGlobalEventDebouncedState,OnGlobalEventDebouncedData>('on-global-event-debounced', {shape: {delay: types.number,eventType: types.oneOfType([types.string, types.symbol]),factory: types.saveHash(types.func),},state: {currentValue: graphTypes.nodeDefinition,},getInitialState() {return {currentValue: pending(),};},operations: {evaluate: {run(node: OnGlobalEventDebouncedNode,operation: never,dependencies: never,context: never,state: OnGlobalEventDebouncedState,): NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<OnGlobalEventDebouncedState, OnGlobalEventDebouncedData>,node: OnGlobalEventDebouncedNode,): void {const { delay, eventType, factory } = node.definition.properties;const debouncedCallback = debounce(() => {this.setState((state) => ({...state,currentValue: factory(),}));}, delay);this.setData({disposeGlobalEventListener: node.scope.globalEvents.listen((event) => {if (event.type !== eventType) return;debouncedCallback();}),});},onUnsubscribe(this: NodeExecutionContext<OnGlobalEventDebouncedState, OnGlobalEventDebouncedData>,): void {const { disposeGlobalEventListener } = this.getData();disposeGlobalEventListener && disposeGlobalEventListener();},},},})

Const OnGlobalEventNodeType

OnGlobalEventNodeType: StatefulNodeType<"on-global-event", OnGlobalEventNodeProperties, OnGlobalEventState, OnGlobalEventData> = createNodeType<'on-global-event',OnGlobalEventNodeProperties,OnGlobalEventState,OnGlobalEventData>('on-global-event', {shape: {eventType: types.oneOfType([types.string, types.symbol]),factory: types.saveHash(types.func),},state: {currentValue: graphTypes.nodeDefinition,},getInitialState() {return {currentValue: pending(),};},operations: {evaluate: {run(node: OnGlobalEventNode,operation: never,dependencies: never,context: never,state: OnGlobalEventState,): NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<OnGlobalEventState, OnGlobalEventData>,node: OnGlobalEventNode,): void {const { eventType, factory } = node.definition.properties;this.setData({disposeGlobalEventListener: node.scope.globalEvents.listen((event) => {if (event.type !== eventType) return;this.setState((state) => ({...state,currentValue: factory(),}));}),});},onUnsubscribe(this: NodeExecutionContext<OnGlobalEventState, OnGlobalEventData>): void {const { disposeGlobalEventListener } = this.getData();disposeGlobalEventListener && disposeGlobalEventListener();},},},})

Const OnNodeType

OnNodeType: StatefulNodeType<"on", OnNodeProperties, OnNodeState> = createNodeType<'on',OnNodeProperties,OnNodeState>('on', {state: {currentValue: types.optional(graphTypes.nodeDefinition),},shape: {initialValue: graphTypes.nodeDefinition,callback: types.saveHash(types.func),},getInitialState(): OnNodeState {return {currentValue: undefined,};},operations: {evaluate: {run(node: OnNode,options: never,dependencies: Array<never>,context: Array<never>,state: OnNodeState,): NodeDefinition {const { currentValue } = state;return currentValue || node.definition.properties.initialValue;},onSubscribe(node: OnNode) {const { callback } = node.definition.properties;const { subscription: existingSubscription } = this.getData();if (existingSubscription) {existingSubscription();}const subscription = node.scope.events.listen((event) => {const updatedValue = callback(event, getParams(node.context));if (updatedValue) {this.setState((prevState) => ({...prevState,currentValue: updatedValue,}));}});this.setData({subscription,});},onUnsubscribe(node: OnNode) {const { subscription: existingSubscription } = this.getData();if (existingSubscription) {existingSubscription();}},},reset: {run(node: OnNode,options: never,dependencies: Array<never>,context: Array<never>,state: OnNodeState,): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<OnNodeState, OnNodeData>, node: OnNode): void {const { currentValue: previousValue } = this.getState();if (!previousValue) {return;}this.setState((prevState) => ({...prevState,currentValue: undefined,}));},},},})

The implementation of the on node. See the on documentation to find out more.

Const OnStreamEmissionNodeType

OnStreamEmissionNodeType: StatefulNodeType<"on-stream-emission", OnStreamEmissionNodeProperties, OnStreamEmissionState, OnStreamEmissionData> = createNodeType<'on-stream-emission',OnStreamEmissionNodeProperties,OnStreamEmissionState,OnStreamEmissionData>('on-stream-emission', {shape: {factory: types.saveHash(types.func),stream: types.saveHash(types.any),},state: {currentValue: graphTypes.nodeDefinition,},getInitialState() {return {currentValue: pending(),};},operations: {evaluate: {run(node: OnStreamEmissionNode,operation: never,dependencies: never,context: never,state: OnStreamEmissionState,): NodeDefinition {return state.currentValue;},onSubscribe(this: NodeExecutionContext<OnStreamEmissionState, OnStreamEmissionData>,node: OnStreamEmissionNode,): void {const { factory, stream } = node.definition.properties;this.setData({streamSubscription: stream.subscribe(() => {this.setState((state) => ({...state,currentValue: factory(),}));}),});},onUnsubscribe(this: NodeExecutionContext<OnStreamEmissionState, OnStreamEmissionData>): void {const { streamSubscription } = this.getData();streamSubscription && streamSubscription.unsubscribe();},},},})

Const OnceNodeType

OnceNodeType: StatefulNodeType<"once", OnceNodeProperties, OnceNodeState, OnceNodeData> = createNodeType<'once', OnceNodeProperties, OnceNodeState, OnceNodeData>('once', {state: {currentValue: types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),},shape: {target: types.oneOfType<NodeDefinition | GraphNode | NodeDependency>([graphTypes.nodeDefinition,graphTypes.graphNode,graphTypes.nodeDependency,]),},getInitialState(): OnceNodeState {return {currentValue: pending(),};},operations: {evaluate: {cacheable: false,run(node: OnceNode,options: never,dependencies: Array<never>,context: Array<never>,state: OnceNodeState,): NodeDefinition | GraphNode {const { currentValue } = state;return currentValue;},onSubscribe(node: OnceNode): void {const { target } = node.definition.properties;this.setState((prevState) => ({...prevState,currentValue: resolve([isGraphNode(target) || isNodeDefinition(target) ? { target } : target],([result]: [GraphNode]) => {this.setState((state: OnceNodeState): OnceNodeState => ({...state,currentValue: result,}),);return result;},),}));},},},})

The implementation of the once node. See the once documentation to learn more.

Const OptimisticNodeType

OptimisticNodeType: StatefulNodeType<"optimistic", OptimisticNodeProperties> = createNodeType<'optimistic', OptimisticNodeProperties>('optimistic', {shape: {target: graphTypes.nodeDefinition,},state: {pendingSetOperations: types.arrayOf(types.string),setResults: types.objectOf(graphTypes.graphNode),value: types.optional(graphTypes.graphNode),},getInitialState(): OptimisticNodeState {return {pendingSetOperations: [],setResults: {},value: undefined,};},operations: {evaluate: {run(node: OptimisticNode,operation: never,dependencies: never,context: never,state: OptimisticNodeState,): GraphNode | NodeDefinition {return state.value || node.definition.properties.target;},},isUpdating: {run(node: OptimisticNode,operation: never,dependencies: never,context: never,state: OptimisticNodeState,): NodeDefinition {return value(state.pendingSetOperations.length > 0);},},set: {run(node: OptimisticNode,operation: SetOperation,dependencies: never,context: never,state: OptimisticNodeState,): GraphNode {return state.setResults[operation.id];},onSubscribe(this: NodeExecutionContext<OptimisticNodeState, OptimisticNodeData>,node: OptimisticNode,operation: SetOperation,): void {const { target } = node.definition.properties;const nodeToResolve = withScopeFrom(node, set(target, operation.properties.value));this.setState((state) => ({...state,pendingSetOperations: [...state.pendingSetOperations, operation.id],setResults: {...state.setResults,[operation.id]: withScopeFrom(node, ok()),},value: withScopeFrom(node, operation.properties.value),}));const unsubscribe = node.scope.store.subscribe(nodeToResolve,resolveOperation(),(value) => {if (PendingNodeType.is(value)) return;this.setState((state) => ({...state,pendingSetOperations: state.pendingSetOperations.filter((id) => id !== operation.id),setResults: ErrorNodeType.is(value)? {...state.setResults,[operation.id]: value,}: state.setResults,value: ErrorNodeType.is(value) ? undefined : value,}));},);this.setData((data) => ({...data,setSubscriptions: {...data.setSubscriptions,[operation.id]: unsubscribe,},}));},onUnsubscribe(this: NodeExecutionContext<OptimisticNodeState, OptimisticNodeData>,node: OptimisticNode,operation: SetOperation,): void {const unsubscribe = this.getData().setSubscriptions![operation.id];unsubscribe();this.setData((data) => ({...data,setSubscriptions: omit(data.setSubscriptions, operation.id),}));this.setState((state) => ({...state,pendingSetOperations: state.pendingSetOperations.filter((id) => id !== operation.id),setResults: omit(state.setResults, operation.id),}));},},},})

The implementation of the optimistic node. See the optimistic documentation to learn more.

Const OrNodeType

OrNodeType: StatelessNodeType<"or", OrNodeProperties> = createNodeType<'or',OrNodeProperties>('or', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: OrNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Or node operands must resolve to value() nodes', {expected: ValueNodeType,received: node.definition,});},},}));},run(node: OrNode, options: never, operands: Array<ValueNode<any>>): NodeDefinition {return value(operands.some((operand) => Boolean(operand.definition.properties.value)));},},},})

The implementation of the or node. See the or documentation to learn more.

Const OtherwiseNodeType

OtherwiseNodeType: StaticNodeType<"otherwise", OtherwiseNodeProperties> = createNodeType<'otherwise', OtherwiseNodeProperties>('otherwise', {shape: {value: graphTypes.nodeDefinition,},})

The implementation of the otherwise node. See the otherwise documentation to learn more.

Const PARAM_NAME_PREFIX

PARAM_NAME_PREFIX: "$$param:" = "$$param:"

Const PARENT

PARENT: unique symbol = Symbol('PARENT')

Const PARENT_SCOPE_PATH_KEY

PARENT_SCOPE_PATH_KEY: unique symbol = Symbol('PARENT_SCOPE_PATH_KEY')

Const PATH_KEY

PATH_KEY: unique symbol = Symbol('PATH_KEY')

Const PENDING

PENDING: never = {} as never

Const PROXIED_NODE

PROXIED_NODE: unique symbol = Symbol('muster::PROXIED_NODE')

Const PROXIED_NODE_DEFINITION

PROXIED_NODE_DEFINITION: unique symbol = Symbol('muster::PROXIED_NODE_DEFINITION')

Const ParallelNodeType

ParallelNodeType: StatelessNodeType<"parallel", ParallelNodeProperties> = createNodeType<'parallel', ParallelNodeProperties>('parallel', {shape: {operations: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {cacheable: false,getDependencies({ operations }: ParallelNodeProperties): Array<NodeDependency> {return operations.map((operation) => ({ target: operation, once: true }));},run(node: ParallelNode, options: never, dependencies: Array<GraphNode>): NodeDefinition {return array(dependencies.map((node) => node.definition));},},},})

The implementation of the parallel node. See the parallel documentation to learn more.

Const ParamNodeType

ParamNodeType: StatelessNodeType<"param", ParamNodeProperties> = createNodeType<'param',ParamNodeProperties>('param', {shape: {name: types.string,},operations: {evaluate: {getContextDependencies({ name }: ParamNodeProperties): [ContextDependency] {return [{ name: getParamContextId(name), required: true, until: shallow }];},run(node: ParamNode,options: never,dependencies: Array<never>,[paramNode]: [ValueNode<ChildKey>],): GraphNode {return paramNode;},},},})

The implementation of the param node. See the param documentation to learn more.

Const ParentNodeType

ParentNodeType: StatelessNodeType<"parent"> = createNodeType<'parent'>('parent', {operations: {evaluate: {getContextDependencies(): [ContextDependency] {return [{name: PARENT,required: false,until: shallow,defaultValue: error('Cannot resolve parent of root node'),},];},run(node: ParentNode,options: never,dependencies: Array<never>,[parentNode]: [GraphNode],): GraphNode {return parentNode;},},},})

The implementation of the parent node. See the parent documentation to learn more.

Const ParseFloatNodeType

ParseFloatNodeType: StatelessNodeType<"parse-float", ParseFloatNodeProperties> = createNodeType<'parse-float', ParseFloatNodeProperties>('parse-float', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: ParseFloatNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(ParseFloatNodeType, 'subject'),},];},run(node: ParseFloatNode,options: never,[subject]: [ValueNode<string>, ValueNode<number>],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;return value(Number.parseFloat(subjectValue));},},},})

The implementation of the parseFloat node. See the parseFloat documentation to learn more.

Const ParseIntNodeType

ParseIntNodeType: StatelessNodeType<"parse-int", ParseIntNodeProperties> = createNodeType<'parse-int', ParseIntNodeProperties>('parse-int', {shape: {radix: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ radix, subject }: ParseIntNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(ParseIntNodeType, 'subject'),},{target: radix,until: untilPositiveIntegerValueNode(ParseIntNodeType, 'radix'),},];},run(node: ParseIntNode,options: never,[subject, radix]: [ValueNode<string>, ValueNode<number>],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const radixValue = radix.definition.properties.value;return value(Number.parseInt(subjectValue, radixValue));},},},})

The implementation of the parseInt node. See the parseInt documentation to learn more.

Const PartialNodeType

PartialNodeType: StatelessNodeType<"partial", PartialNodeProperties> = createNodeType<'partial',PartialNodeProperties>('partial', {shape: {args: types.oneOfType([types.objectOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),types.arrayOf(types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])),]),target: graphTypes.nodeDefinition,},operations: {call: {getDependencies({ target }: PartialNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsCallOperation,},];},run(node: PartialNode,operation: CallOperation,[target]: [GraphNode],): NodeDefinition | GraphAction {const { args } = node.definition.properties;const { args: inputArgs } = operation.properties;if (isCallArgumentMap(args)) {// Handle the named arguments mapif (inputArgs && !isCallArgumentMap(inputArgs)) {return error(getInvalidTypeError('A partial node was called with unexpected type of arguments.', {expected: 'Named arguments',received: 'Array of arguments',}),);}const combinedArgs = inputArgs ? { ...inputArgs, ...args } : args;const argsGraphNodes = mapValues(combinedArgs, (arg) =>isGraphNode(arg) ? arg : withScopeFrom(node, arg),);return createGraphAction(target, callOperation(argsGraphNodes));}// Handle the positional argumentsif (inputArgs && !isCallArgumentArray(inputArgs)) {return error(getInvalidTypeError('A partial node was called with unexpected type of arguments.', {expected: 'Array of arguments',received: 'Named arguments',}),);}const combinedArgs = inputArgs ? [...args, ...inputArgs] : args;const argsGraphNodes = combinedArgs.map((arg) =>isGraphNode(arg) ? arg : withScopeFrom(node, arg),);return createGraphAction(target, callOperation(argsGraphNodes));},},},})

The implementation of the partial node. See the partial documentation to learn more.

Const PendingNodeType

PendingNodeType: StaticNodeType<"pending"> = createNodeType<'pending'>('pending')

The implementation of the pending node. See the pending documentation to learn more.

Const PlaceholderNodeType

PlaceholderNodeType: StatefulNodeType<"placeholder", PlaceholderNodeProperties, PlaceholderNodeState, PlaceholderNodeData> = createNodeType<'placeholder',PlaceholderNodeProperties,PlaceholderNodeState,PlaceholderNodeData>('placeholder', {state: {results: types.objectOf(graphTypes.nodeDefinition),},shape: {path: types.arrayOf(types.shape({id: types.string,operation: graphTypes.graphOperation,}),),queryBuilder: types.saveHash(types.any),},serialize: false,deserialize: false,getInitialState(): PlaceholderNodeState {return {results: {},};},operations: {[WILDCARD_OPERATION]: {run(node: PlaceholderNode,operation: GraphOperation,dependencies: never,context: never,state: PlaceholderNodeState,): NodeDefinition | GraphNode {return state.results[operation.id] || pending();},onSubscribe(this: NodeExecutionContext<PlaceholderNodeState, PlaceholderNodeData>,node: PlaceholderNode,operation: GraphOperation,): void {const { path, queryBuilder } = node.definition.properties;const resultNode = stateful<NodeDefinition | GraphNode>(pending());const getOperationDependencies = (): Array<NodeDependency> | undefined => {if (isCallOperation(operation)) {const { args } = operation.properties;if (!args) return [];if (Array.isArray(args)) {return args.map((arg) => ({target: arg,once: true,}));}return Object.keys(args).map((name) => ({target: args[name],once: true,}));}if (isGetItemsOperation(operation)) {return operation.properties.transforms.map((transform) => {const transformNode = isNodeDefinition(transform)? withScopeFrom(node, transform): transform;const resolveTransform = hoistDependencies(transformNode);return { target: resolveTransform.definition };});}return undefined;};let lastResolvedDependenciesIds: Array<string> | undefined;const dependenciesResolved = (resolvedDependencies: Array<GraphNode>): NodeDefinition => {if (lastResolvedDependenciesIds) {const dependenciesHaveChanged = lastResolvedDependenciesIds.some((id, index) => id !== resolvedDependencies[index].id,);if (!dependenciesHaveChanged) {queryBuilder.markAsModified();return resultNode;}}lastResolvedDependenciesIds = resolvedDependencies.map(({ id }) => id);if (isCallOperation(operation)) {const { args } = operation.properties;const argsValues = toNodeDefinitionArray(resolvedDependencies);let resolvedOperation: CallOperation;if (!args) {resolvedOperation = callOperation();} else if (isCallArgumentArray(args)) {// Handle the array of argumentsresolvedOperation = callOperation(argsValues);} else {// Handle the named argumentsresolvedOperation = callOperation(fromPairs(zip(Object.keys(args), argsValues)));}const childPath = [...path, { id: operation.id, operation: resolvedOperation }];const disposeRequest = queryBuilder.addRequest(childPath, (result) =>resultNode.update(assignPlaceholderPath(node, path, result)),);this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: disposeRequest,},}));} else if (isGetChildOperation(operation)) {const childPath = [...path, { id: operation.id, operation }];const dispose = queryBuilder.addRequest(childPath);this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: dispose,},}));return placeholder(queryBuilder, childPath);} else if (isGetItemsOperation(operation)) {const data = this.getData();const disposePreviousGetItems =data.disposeRequest && data.disposeRequest[operation.id];if (disposePreviousGetItems) {disposePreviousGetItems();}const operationWithResolvedTransforms = getItemsOperation(toNodeDefinitionArray(resolvedDependencies),);const childPath = [...path,{ id: operation.id, operation: operationWithResolvedTransforms },];const dispose = queryBuilder.addRequest(childPath, (result) => {resultNode.update(assignPlaceholderPath(node, path, result));});this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: dispose,},}));resultNode.update(placeholder(queryBuilder, childPath));} else if (isIterateOperation(operation)) {const childPath = [...path, { id: operation.id, operation: getItemsOperation() }];resultNode.update(placeholder(queryBuilder, childPath));const dispose = queryBuilder.addRequest(childPath, (result) => {resultNode.update(assignPlaceholderPath(node, path, toIteratorResult(result)));});this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: dispose,},}));} else if (isSetOperation(operation)) {this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: queryBuilder.addRequest([...path, { id: operation.id, operation }],(result) => {resultNode.update(assignPlaceholderPath(node,path,isOkNodeDefinition(result) ? operation.properties.value : result,),);},),},}));} else {this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: queryBuilder.addRequest([...path, { id: operation.id, operation }],(result) => {resultNode.update(assignPlaceholderPath(node, path, result));},),},}));}return resultNode;};const dependencies = getOperationDependencies();if (dependencies && dependencies.length > 0) {this.setState((state) => ({...state,results: {...state.results,[operation.id]: resolve(dependencies, dependenciesResolved),},}));} else {this.setState((state) => ({...state,results: {...state.results,[operation.id]: dependenciesResolved([]),},}));}},onInvalidate(this: NodeExecutionContext<PlaceholderNodeState, PlaceholderNodeData>,node: PlaceholderNode,operation: GraphOperation,): void {if (!isEvaluateOperation(operation)) return;const results = this.getState().results;const { path, queryBuilder } = node.definition.properties;const resultNode =results && results[operation.id]? (results[operation.id] as ExternalStatefulNodeDefinition<NodeDefinition | GraphNode>): stateful<NodeDefinition | GraphNode>(pending());this.setData((data) => ({...data,disposeRequest: {...data.disposeRequest,[operation.id]: queryBuilder.addRequest([...path, { id: operation.id, operation }],(result) => {resultNode.update(assignPlaceholderPath(node, path, result));},),},}));this.setState((state) => ({...state,results: {...state.results,[operation.id]: resultNode,},}));},onUnsubscribe(this: NodeExecutionContext<PlaceholderNodeState, PlaceholderNodeData>,node: PlaceholderNode,operation: GraphOperation,): void {const { disposeRequest } = this.getData();const disposeCurrentRequest = disposeRequest && disposeRequest[operation.id];if (disposeCurrentRequest) {disposeCurrentRequest();this.setData((data) => ({...data,disposeRequest: omit(data.disposeRequest, operation.id),}));}this.setState((state) => ({...state,results: omit(state.results, operation.id),}));},},},})

An implementation of the placeholder node. See the placeholder documentation to find out more.

Const PopNodeType

PopNodeType: StatefulNodeType<"pop", PopNodeProperties, PopNodeState, __type> = createNodeType<'pop', PopNodeProperties, PopNodeState, {}>('pop', {shape: {id: types.number,target: graphTypes.nodeDefinition,},state: {currentValue: types.optional(graphTypes.nodeDefinition),},getInitialState() {return {currentValue: undefined,};},operations: {evaluate: {cacheable: false,run(node: PopNode,options: never,dependencies: never,context: never,state: PopNodeState,): GraphNode {return state.currentValue!;},onSubscribe(this: NodeExecutionContext<PopNodeState, {}>, node: PopNode): void {if (this.getState().currentValue) return;const { target } = node.definition.properties;this.setState(() => ({currentValue: withScopeFrom(node,resolve([{ target, until: untilSupportsPopOperation }], ([resolvedTarget]) => {return withScopeFrom(resolvedTarget,resolve([createGraphAction(resolvedTarget, popOperation())], ([result]) => {this.setState(() => ({ currentValue: result }));return result;}),);}),),}));},},},})

The implementation of the pop. See the pop documentation for more information.

Const PopOperationType

PopOperationType: OperationType<"pop", PopProperties> = createOperationType<'pop',PopProperties>('pop', {cacheable: false,shape: {},})

An implementation of the popOperation. See the popOperation documentation to find out more.

Const PowNodeType

PowNodeType: StatelessNodeType<"pow", PowNodeProperties> = createNodeType<'pow',PowNodeProperties>('pow', {shape: {base: graphTypes.nodeDefinition,exponent: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ base, exponent }: PowNodeProperties): Array<NodeDependency> {return [{target: base,until: untilNumberValueNode(PowNodeType, 'base'),},{target: exponent,until: untilNumberValueNode(PowNodeType, 'exponent'),},];},run(node: PowNode,options: never,[base, exponent]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {return value(Math.pow(base.definition.properties.value, exponent.definition.properties.value),);},},},})

The implementation of the pow node. See the pow documentation to learn more.

Const PropertyNodeType

PropertyNodeType: StatelessNodeType<"property", PropertyNodeProperties> = createNodeType<'property', PropertyNodeProperties>('property', {shape: {subject: graphTypes.nodeDefinition,path: types.arrayOf(types.string),},operations: {evaluate: {getDependencies({ subject }: PropertyNodeProperties): Array<NodeDependency> {return [{target: subject,until: {predicate: ValueNodeType.is,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage('Property node subject must resolve to a value() node',{expected: ValueNodeType,received: node.definition,},);},},},];},run(node: PropertyNode,options: never,[subjectNode]: [ValueNode<any>],): NodeDefinition | GraphNode {const { path } = node.definition.properties;const subject = subjectNode.definition.properties.value;return value(getPath(subject, path));},},},})

The implementation of the property node. See the property documentation to learn more.

Const ProxyNodeType

ProxyNodeType: StatelessNodeType<"proxy", ProxyNodeProperties> = createNodeType<'proxy',ProxyNodeProperties>('proxy', {shape: {middlewares: types.arrayOf(graphTypes.nodeDefinition),queryBuilder: types.saveHash(types.any),schedulerFactory: types.saveHash(types.func),},serialize: false,deserialize: false,operations: {evaluate: {run(node: ProxyNode): NodeDefinition {const { middlewares, queryBuilder, schedulerFactory } = node.definition.properties;const composedMiddleware = composeMiddlewares(transformMiddlewares(middlewares, node));let lastResult: NodeDefinition = ok();let lastSnapshot: QueriesSnapshot | undefined = undefined;return takeLast([schedulerFactory(() => {if (!queryBuilder.isModified) return lastResult;queryBuilder.resetModifiedState();const queryBuilderSnapshot = getQueryBuilderSnapshot(queryBuilder);if (lastSnapshot && isEqual(lastSnapshot, queryBuilderSnapshot)) return lastResult;lastSnapshot = queryBuilderSnapshot;const querySetWithCallback = buildQuerySetFromQueryBuilderSnapshot(queryBuilderSnapshot,queryBuilder,);const traverseRequest = traverse(composedMiddleware,requestOperation(querySetWithCallback.node, {}),);lastResult = resolve([{ target: traverseRequest, allowErrors: true }],([result]: [GraphNode]) => {querySetWithCallback.callback(result.definition);return ok();},);return lastResult;}),placeholder(queryBuilder, []),]);},},},})

Const PushNodeType

PushNodeType: StatefulNodeType<"push", PushNodeProperties, PushNodeState, __type> = createNodeType<'push', PushNodeProperties, PushNodeState, {}>('push', {shape: {item: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,},state: {memoized: types.saveHash(types.func),},getInitialState() {return {memoized: once((target: GraphNode, item: NodeDefinition) =>createGraphAction(target, pushOperation(item)),),};},operations: {evaluate: {cacheable: false,getDependencies({ target }: PushNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsPushOperation,},];},run(node: PushNode,options: never,[target]: [GraphNode],context: never,state: PushNodeState,): GraphAction {return state.memoized(target, node.definition.properties.item);},},},})

The implementation of the push. See the push documentation for more information.

Const PushOperationType

PushOperationType: OperationType<"push", PushProperties> = createOperationType<'push',PushProperties>('push', {cacheable: false,shape: {value: graphTypes.nodeDefinition,},})

An implementation of the pushOperation. See the pushOperation documentation to find out more.

Const QueryNodeType

QueryNodeType: StatefulNodeType<"query", QueryNodeProperties> = createNodeType<'query',QueryNodeProperties,QueryNodeState,QueryNodeData>('query', {shape: {keys: graphTypes.nodeDefinition,root: graphTypes.nodeDefinition,},state: {result: types.oneOfType([graphTypes.graphNode, graphTypes.nodeDefinition]),},getInitialState(): QueryNodeState {return {result: pending(),};},operations: {evaluate: {run(node: QueryNode,operation: never,dependencies: never,context: never,state: QueryNodeState,): NodeDefinition | GraphNode {return state.result;},onSubscribe(this: NodeExecutionContext<QueryNodeState, QueryNodeData>,node: QueryNode,): void {let previousResponse: NodeDefinition | undefined;try {const { keys, root } = node.definition.properties;const { querySet, responseAssembler } = buildQuerySetForQuery(root, keys);this.setData({disposeQuerySetSubscription: node.scope.store.subscribe(withScopeFrom(node, querySet),resolveOperation(),(response) => {if (ErrorNodeType.is(response) || PendingNodeType.is(response)) {this.setState({result: response,});return;}const newResponse = safelyGetValueFromResponse(response, responseAssembler);if (previousResponse && newResponse.type === previousResponse.type) {if (isValueNodeDefinition(newResponse) &&isValueNodeDefinition(previousResponse) &&isEqual(newResponse.properties.value, previousResponse.properties.value)) {return;}}previousResponse = newResponse;this.setState({result: newResponse,});},),});} catch (ex) {this.setState({result: isErrorNodeDefinition(ex) ? ex : error(ex),});}},onUnsubscribe(this: NodeExecutionContext<QueryNodeState, QueryNodeData>): void {const { disposeQuerySetSubscription } = this.getData();disposeQuerySetSubscription && disposeQuerySetSubscription();},},},})

The implementation of the query node. See the query documentation to learn more.

Const QuerySetCallOperationNodeType

QuerySetCallOperationNodeType: StatelessNodeType<"query-set-call-operation", QuerySetCallOperationNodeProperties> = createNodeType<'query-set-call-operation', QuerySetCallOperationNodeProperties>('query-set-call-operation',{shape: {operation: graphTypes.graphOperation,},operations: {},},)

Const QuerySetCatchErrorNodeType

QuerySetCatchErrorNodeType: StaticNodeType<"query-set-catch-error", QuerySetCatchErrorNodeProperties> = createNodeType<'query-set-catch-error', QuerySetCatchErrorNodeProperties>('query-set-catch-error',{deserialize: false,serialize: false,shape: {fallbackGenerator: types.saveHash(types.func),target: graphTypes.nodeDefinition,},},)

Const QuerySetDeferNodeType

QuerySetDeferNodeType: StaticNodeType<"query-set-defer", QuerySetDeferNodeProperties> = createNodeType<'query-set-defer', QuerySetDeferNodeProperties>('query-set-defer', {deserialize: false,serialize: false,shape: {fallbackGenerator: types.saveHash(types.func),target: graphTypes.nodeDefinition,},})

Const QuerySetGetChildOperationNodeType

QuerySetGetChildOperationNodeType: StaticNodeType<"query-set-get-child-operation", QuerySetGetChildOperationNodeProperties> = createNodeType<'query-set-get-child-operation', QuerySetGetChildOperationNodeProperties>('query-set-get-child-operation',{shape: {children: types.optional(types.arrayOf(graphTypes.nodeDefinition)),operation: graphTypes.graphOperation,},},)

Const QuerySetGetItemsOperationNodeType

QuerySetGetItemsOperationNodeType: StaticNodeType<"query-set-get-items-operation", QuerySetGetItemsOperationNodeProperties> = createNodeType<'query-set-get-items-operation', QuerySetGetItemsOperationNodeProperties>('query-set-get-items-operation',{shape: {children: types.optional(types.arrayOf(graphTypes.nodeDefinition)),operation: graphTypes.graphOperation,},},)

Const QuerySetIsPendingNodeType

QuerySetIsPendingNodeType: StaticNodeType<"query-set-is-pending", QuerySetIsPendingNodeProperties> = createNodeType<'query-set-is-pending', QuerySetIsPendingNodeProperties>('query-set-is-pending',{deserialize: false,serialize: false,shape: {target: graphTypes.nodeDefinition,},},)

Const QuerySetNodeType

QuerySetNodeType: StatelessNodeType<"query-set", QuerySetNodeProperties> = createNodeType<'query-set', QuerySetNodeProperties>('query-set', {shape: {children: types.optional(types.arrayOf(graphTypes.nodeDefinition)),options: types.shape({bubbleErrorsToTop: types.bool,}),root: graphTypes.nodeDefinition,},operations: {evaluate: {run(node: QuerySetNode): NodeDefinition {const { children, options, root } = node.definition.properties;return resolveOperations(withScopeFrom(node, root), children, withScopeFrom(node,value(options),) as ValueNode<QuerySetOptions>);},},},})

Const QuerySetOperationNodeType

QuerySetOperationNodeType: StaticNodeType<"query-set-operation", QuerySetOperationNodeProperties> = createNodeType<'query-set-operation', QuerySetOperationNodeProperties>('query-set-operation', {shape: {children: types.optional(types.arrayOf(graphTypes.nodeDefinition)),operation: graphTypes.graphOperation,},})

Const QuerySetResultNodeType

QuerySetResultNodeType: StatefulNodeType<"query-set-result", QuerySetResultNodeProperties, QuerySetResultNodeState, QuerySetResultNodeData> = createNodeType<'query-set-result',QuerySetResultNodeProperties,QuerySetResultNodeState,QuerySetResultNodeData>('query-set-result', {shape: {queries: types.arrayOf(graphTypes.nodeDefinition),result: graphTypes.nodeDefinition,},state: {},getInitialState() {return {};},operations: {call: {run(node: QuerySetResultNode, operation: CallOperation): NodeDefinition {const { queries, result } = node.definition.properties;const queryIndex = queries.findIndex((query) =>isQuerySetCallOperationNodeDefinition(query) &&query.properties.operation.id === operation.id,);if (queryIndex === -1) {return error(`Could not find 'call' result for operation: ${operation.id}`);}const query = queries[queryIndex] as QuerySetOperationNodeDefinition;const queryResult = result.properties.items[queryIndex];if (!query.properties.children) {return queryResult;}if (!isArrayNodeDefinition(queryResult)) {return error(getInvalidTypeErrorMessage('Invalid query result', {expected: ArrayNodeType,received: queryResult,}),);}return querySetResult(query.properties.children, queryResult);},},evaluate: {run(node: QuerySetResultNode): NodeDefinition {const { queries, result } = node.definition.properties;const queryIndex = queries.findIndex((query) =>isQuerySetOperationNodeDefinition(query) &&(isEvaluateOperation(query.properties.operation) ||isResolveOperation(query.properties.operation)),);if (queryIndex === -1) {return error('Node does not support `evaluate` operation.');}const query = queries[queryIndex] as QuerySetOperationNodeDefinition;const queryResult = result.properties.items[queryIndex];if (!query.properties.children) {return queryResult;}if (!isArrayNodeDefinition(queryResult)) {return error(getInvalidTypeErrorMessage('Invalid query result', {expected: ArrayNodeType,received: queryResult,}),);}return querySetResult(query.properties.children, queryResult);},},getChild: {run(node: QuerySetResultNode, operation: GetChildOperation): NodeDefinition {const { queries, result } = node.definition.properties;const queryIndex = queries.findIndex((query) =>isQuerySetGetChildOperationNodeDefinition(query) &&query.properties.operation.id === operation.id,);if (queryIndex === -1) {const { key } = operation.properties;return notFound(`Could not find 'getChild' result for key: ${getType(key)}`);}const query = queries[queryIndex] as QuerySetGetChildOperationNodeDefinition;const queryResult = result.properties.items[queryIndex];if (!query.properties.children) {return queryResult;}if (!isArrayNodeDefinition(queryResult)) {return error(getInvalidTypeErrorMessage('Invalid query result', {expected: ArrayNodeType,received: queryResult,}),);}return querySetResult(query.properties.children, queryResult);},},getItems: {run(node: QuerySetResultNode, operation: GetItemsOperation): NodeDefinition {const { queries, result } = node.definition.properties;const queryIndex = queries.findIndex((query) =>isQuerySetGetItemsOperationNodeDefinition(query) &&(query.properties.operation? query.properties.operation.id === operation.id: operation.properties.transforms.length === 0),);if (queryIndex === -1) {return error(`Could not find 'getItems' result for operation: ${operation.id}.`);}const query = queries[queryIndex] as QuerySetGetItemsOperationNodeDefinition;const queryResult = result.properties.items[queryIndex];if (!query.properties.children) {return queryResult;}if (!isArrayNodeDefinition(queryResult)) {return error(getInvalidTypeErrorMessage('Invalid query result', {expected: ArrayNodeType,received: queryResult,}),);}return querySetResult(query.properties.children, queryResult);},},set: {run(node: QuerySetResultNode, operation: CallOperation): NodeDefinition {const { queries, result } = node.definition.properties;const queryIndex = queries.findIndex((query) =>isQuerySetSetOperationNodeDefinition(query) &&query.properties.operation.id === operation.id,);if (queryIndex === -1) {return error(`Could not find 'set' result for operation: ${operation.id}`);}const query = queries[queryIndex] as QuerySetGetItemsOperationNodeDefinition;const queryResult = result.properties.items[queryIndex];if (!query.properties.children) {return queryResult;}if (!isArrayNodeDefinition(queryResult)) {return error(getInvalidTypeErrorMessage('Invalid query result', {expected: ArrayNodeType,received: queryResult,}),);}return querySetResult(query.properties.children, queryResult);},},},})

Const QuerySetSetOperationNodeType

QuerySetSetOperationNodeType: StatelessNodeType<"query-set-set-operation", QuerySetSetOperationNodeProperties> = createNodeType<'query-set-set-operation', QuerySetSetOperationNodeProperties>('query-set-set-operation',{shape: {operation: graphTypes.graphOperation,},operations: {},},)

Const QuoteNodeType

QuoteNodeType: StaticNodeType<"quote", QuoteNodeProperties> = createNodeType<'quote',QuoteNodeProperties>('quote', {shape: {node: graphTypes.nodeDefinition,},})

The implementation of the quote node. See the quote documentation to learn more.

Const ROOT_CONTEXT_NAME

ROOT_CONTEXT_NAME: unique symbol = Symbol('ROOT')

Const ReduceNodeType

ReduceNodeType: StatelessNodeType<"reduce", ReduceNodeProperties> = createNodeType<'reduce',ReduceNodeProperties>('reduce', {shape: {source: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),reducer: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),initialState: types.any,},operations: {evaluate: {getDependencies({ source }: ReduceNodeProperties): Array<NodeDependency> {return [{target: source,until: untilSupportsIterateOperation,},];},run(node: ReduceNode, options: never, [iterable]: [GraphNode]): NodeDefinition {const { initialState, reducer } = node.definition.properties;return getNextIteratorResult(iterable, (iteratorResult) => {if (NilNodeType.is(iteratorResult)) {return withScopeFrom(iterable, value(initialState));}const { value: itemValue, next: nextIterator } = iteratorResult.definition.properties;const item = isGraphNode(itemValue)? itemValue: withScopeFrom(iteratorResult, itemValue);return withScopeFrom(iteratorResult,applyReducerStep(reducer, initialState, item, (transformedResult) => {if (DoneNodeType.is(transformedResult)) {const resultValue = transformedResult.definition.properties.value!;return withScopeFrom(transformedResult,resolve([{target: resultValue,until: untilValidReducerStep,},],([finalValue]: [ValueNode<any>]) => finalValue,),);}const { value: updatedState } = transformedResult.definition.properties;if (!nextIterator) {return withScopeFrom(transformedResult, value(updatedState));}const nextIteratorNode = isGraphNode(nextIterator)? nextIterator: withScopeFrom(iteratorResult, nextIterator);const nextResult = reduce(nextIteratorNode, reducer, updatedState);return withScopeFrom(node, nextResult);}),);});},},},})

Const RegexNodeType

RegexNodeType: StaticNodeType<"regex", RegexNodeProperties, SerializedRegexNodeProperties> = createNodeType<'regex', RegexNodeProperties, SerializedRegexNodeProperties>('regex', {shape: {pattern: types.oneOfType([types.string, types.saveHash(types.any)]),},serialize(properties: RegexNodeProperties): SerializedRegexNodeProperties {return {pattern: { source: properties.pattern.source, flags: properties.pattern.flags },};},deserialize(properties: SerializedRegexNodeProperties): RegexNodeProperties {return {pattern: new RegExp(properties.pattern.source, properties.pattern.flags),};},})

The implementation of the regex node. See the regex documentation to learn more.

Const RemoteMiddlewareNodeTypes

RemoteMiddlewareNodeTypes: Array<NodeType> = [// CacheMiddlewareNodeType,CombinedMiddlewareNodeType,FromStreamMiddlewareNodeType,MockResponseMiddlewareNodeType,TransformResponseMiddlewareNodeType,XhrMiddlewareNodeType,]

Const RemoteNodeTypes

RemoteNodeTypes: Array<NodeType> = [...RemoteMiddlewareNodeTypes, ProxyNodeType]

Const RemoveItemAtNodeType

RemoveItemAtNodeType: StatefulNodeType<"remove-item-at", RemoveItemAtNodeProperties, RemoveItemAtNodeState, __type> = createNodeType<'remove-item-at', RemoveItemAtNodeProperties, RemoveItemAtNodeState, {}>('remove-item-at',{shape: {index: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,},state: {memoized: types.saveHash(types.func),},getInitialState() {return {memoized: once((target: GraphNode, index: number) =>createGraphAction(target, removeItemAtOperation(index)),),};},operations: {evaluate: {cacheable: false,getDependencies({ target, index }: RemoveItemAtNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsRemoveItemAtOperation,},{target: index,until: untilPositiveValueIndex,},];},run(node: RemoveItemAtNode,options: never,[target, index]: [GraphNode, ValueNode<number>],context: never,state: RemoveItemAtNodeState,): GraphAction {return state.memoized(target, index.definition.properties.value);},},},},)

The implementation of the removeItemAt. See the removeItemAt documentation for more information.

Const RemoveItemAtOperationType

RemoveItemAtOperationType: OperationType<"removeItemAt", RemoveItemAtProperties> = createOperationType<'removeItemAt', RemoveItemAtProperties>('removeItemAt', {cacheable: false,shape: {index: types.number,},})

An implementation of the removeItemAtOperation. See the removeItemAtOperation documentation to find out more.

Const RemoveItemNodeType

RemoveItemNodeType: StatefulNodeType<"remove-item", RemoveItemNodeProperties, RemoveItemNodeState, __type> = createNodeType<'remove-item', RemoveItemNodeProperties, RemoveItemNodeState, {}>('remove-item',{shape: {item: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,},state: {memoized: types.saveHash(types.func),},getInitialState() {return {memoized: lodashOnce((target: GraphNode, id: string) =>createGraphAction(target, removeItemOperation(id)),),};},operations: {evaluate: {cacheable: false,getDependencies({ target, item }: RemoveItemNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsRemoveItemOperation,},{target: once({target: item,until: untilItemWithId,}),until: untilItemWithId,},];},run(node: RemoveItemNode,options: never,[target, item]: [GraphNode, ItemWithIdNode],context: never,state: RemoveItemNodeState,): GraphAction {return state.memoized(target, item.definition.properties.id);},},},},)

The implementation of the removeItem. See the removeItem documentation for more information.

Const RemoveItemOperationType

RemoveItemOperationType: OperationType<"removeItem", RemoveItemProperties> = createOperationType<'removeItem', RemoveItemProperties>('removeItem', {cacheable: false,shape: {id: types.string,},})

An implementation of the removeItemOperation. See the removeItemOperation documentation to find out more.

Const RemoveItemsNodeType

RemoveItemsNodeType: StatefulNodeType<"remove-items", RemoveItemsNodeProperties, RemoveItemsNodeState, __type> = createNodeType<'remove-items', RemoveItemsNodeProperties, RemoveItemsNodeState, {}>('remove-items',{shape: {predicate: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,},state: {memoized: types.saveHash(types.func),},getInitialState() {return {memoized: once((target: GraphNode, predicate: NodeDefinition) =>createGraphAction(target, removeItemsOperation(predicate)),),};},operations: {evaluate: {cacheable: false,getDependencies({ target, predicate }: RemoveItemsNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsRemoveItemsOperation,},];},run(node: RemoveItemsNode,operation: never,[target]: [GraphNode],context: never,state: RemoveItemsNodeState,): GraphAction {const { predicate } = node.definition.properties;return state.memoized(target, predicate);},},},},)

The implementation of the removeItems. See the removeItems documentation for more information.

Const RemoveItemsOperationType

RemoveItemsOperationType: OperationType<"removeItems", RemoveItemsProperties> = createOperationType<'removeItems', RemoveItemsProperties>('removeItems', {cacheable: false,shape: {predicate: graphTypes.nodeDefinition,},})

An implementation of the removeItemsOperation. See the removeItemsOperation documentation to find out more.

Const ReplaceNodeType

ReplaceNodeType: StatelessNodeType<"replace", ReplaceNodeProperties> = createNodeType<'replace',ReplaceNodeProperties>('replace', {shape: {pattern: graphTypes.nodeDefinition,replacePattern: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({pattern,replacePattern,subject,}: ReplaceNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(ReplaceNodeType, 'subject'),},{target: pattern,until: untilStringValueNode(ReplaceNodeType, 'pattern'),},{target: replacePattern,until: untilStringValueNode(ReplaceNodeType, 'replacePattern'),},];},run(node: ReplaceNode,options: never,[subject, pattern, replacePattern]: Array<ValueNode<string>>,): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const patternValue = pattern.definition.properties.value;const replacePatternValue = replacePattern.definition.properties.value;return value((subjectValue || '').replace(patternValue, replacePatternValue));},},},})

The implementation of the replace node. See the replace documentation to learn more.

Const RequestOperationType

RequestOperationType: OperationType<"request", RequestProperties> = createOperationType<'request', RequestProperties>('request', {shape: {metadata: types.objectOf(types.saveHash(types.any)),next: types.optional(graphTypes.graphNode),query: graphTypes.nodeDefinition,},})

An implementation of the requestOperation. See the requestOperation documentation to find out more.

Const ResetNodeType

ResetNodeType: StatelessNodeType<"reset", ResetNodeProperties> = createNodeType<'reset',ResetNodeProperties>('reset', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {cacheable: false,getDependencies({ target }: ResetNodeProperties): [NodeDependency] {return [{target,until: {predicate: supportsResetOperation,errorMessage(node: GraphNode): string {return getInvalidTypeErrorMessage(`${pascalCase(ResetNodeType.name)} target cannot be reset`,{ received: node.definition },);},},},];},run(node: ResetNode, operation: never, [subjectNode]: [ResettableGraphNode]): GraphAction {return createGraphAction(subjectNode, resetOperation());},},},})

The implementation of the reset node. See the reset documentation to learn more.

Const ResetOperationType

ResetOperationType: OperationType<"reset"> = createOperationType('reset', {cacheable: false,})

An implementation of the resetOperation. See the [[resteOperation]] documentation to find out more.

Const ResolveOperationType

ResolveOperationType: OperationType<"resolve", ResolveProperties> = createOperationType<'resolve', ResolveProperties>('resolve', {shape: {until: types.optional(types.shape({predicate: types.saveHash(types.func),errorMessage: types.saveHash(types.func),}),),allowErrors: types.bool,allowPending: types.bool,acceptNil: types.bool,},})

An implementation of the resolveOperation. See the resolveOperation documentation to find out more.

Const ResultOperationType

ResultOperationType: OperationType<"result", ResultProperties<any>> = createOperationType<'result', ResultProperties<any>>('result', {shape: {acc: types.saveHash(types.any),next: types.optional(graphTypes.graphNode),},})

An implementation of the [[resultOperation]]. See the [[resultOperation]] documentation to find out more.

Const RootNodeType

RootNodeType: StatelessNodeType<"root"> = createNodeType<'root'>('root', {operations: {evaluate: {run(node: RootNode): GraphNode {return node.context.values[ROOT_CONTEXT_NAME as any];},},},})

The implementation of the root node. See the root documentation to learn more.

Const RoundNodeType

RoundNodeType: StatelessNodeType<"round", RoundNodeProperties> = createNodeType<'round',RoundNodeProperties>('round', {shape: {target: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target }: RoundNodeProperties): Array<NodeDependency> {return [{ target, until: untilNumberValueNode(RoundNodeType, 'target') }];},run(node: RoundNode, options: never, [target]: [ValueNode<number>]): NodeDefinition {return toValue(Math.round(target.definition.properties.value));},},},})

The implementation of the round node. See the round documentation to learn more.

Const SCOPE

SCOPE: unique symbol = Symbol.for('muster::SCOPE')

Const ScopeNodeType

ScopeNodeType: StatefulNodeType<"scope", ScopeNodeProperties, ScopeNodeState, ScopeNodeData> = createNodeType<'scope', ScopeNodeProperties, ScopeNodeState, ScopeNodeData>('scope', {shape: {context: types.optional(types.objectOf(types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),),),root: graphTypes.nodeDefinition,redispatch: types.optional(types.oneOfType([types.saveHash(types.func), types.bool])),},state: {scope: types.optional(graphTypes.scope),context: types.optional(graphTypes.context),},getInitialState() {return {scope: undefined,context: undefined,};},onSubscribe(this: NodeExecutionContext<ScopeNodeState, ScopeNodeData>, node: ScopeNode): void {const { root, context, redispatch } = node.definition.properties;const childScope = createChildScope(node.scope, {redispatch,onSubscribe: () => this.retain(),onUnsubscribe: () => this.release(),});const childContext = createRootContext({...(context &&mapValues(context, (contextValue) =>isGraphNode(contextValue) ? contextValue : withScopeFrom(node, contextValue),)),[PARENT_SCOPE_PATH_KEY]: withScopeFrom(node, value(getPath(node.context))),});// TODO: Remove the `as any` cast once https://github.com/Microsoft/TypeScript/issues/1863 is resolvedchildContext.values[ROOT_CONTEXT_NAME as any] = createGraphNode(childScope, childContext, root);this.setState((prevState): ScopeNodeState => ({...prevState,scope: childScope,context: childContext,}),);const scopeDefinition = node.definition as ScopeNodeDefinition;scopeDefinition.activeScopes.push(childScope);},onUnsubscribe(this: NodeExecutionContext<ScopeNodeState, ScopeNodeData>, node: ScopeNode): void {const { scope } = this.getState();if (!scope) {return;}const scopeDefinition = node.definition as ScopeNodeDefinition;const scopeIndex = scopeDefinition.activeScopes.indexOf(scope);if (scopeIndex !== -1) {scopeDefinition.activeScopes.splice(scopeIndex, 1);}},operations: {evaluate: {run(node: ScopeNode,options: never,dependencies: Array<never>,contextDependencies: Array<never>,state: ScopeNodeState,): NodeDefinition | GraphNode {const { root } = node.definition.properties;const { scope, context } = state;return createGraphNode(scope!, context!, root);},},},})

The implementation of the scope node. See the scope documentation to learn more.

Const SentenceCaseNodeType

SentenceCaseNodeType: StatelessNodeType<"sentence-case", SentenceCaseNodeProperties> = createNodeType<'sentence-case', SentenceCaseNodeProperties>('sentence-case', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: SentenceCaseNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(SentenceCaseNodeType, 'subject'),},];},run(node: SentenceCaseNode, options: never, [subject]: [ValueNode<string>]): NodeDefinition {if (NilNodeType.is(subject)) return nil();return value(upperFirst(subject.definition.properties.value));},},},})

The implementation of the sentenceCase node. See the sentenceCase documentation to learn more.

Const SeriesNodeType

SeriesNodeType: StatelessNodeType<"series", SeriesNodeProperties> = createNodeType<'series',SeriesNodeProperties>('series', {shape: {operations: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {cacheable: false,getDependencies({ operations }: SeriesNodeProperties): Array<NodeDependency> {return operations.length > 0 ? [{ target: operations[0], once: true }] : [];},run(node: SeriesNode, options: never, [result]: [GraphNode]): NodeDefinition {const operations = node.definition.properties.operations;if (operations.length === 0) return value(undefined);if (operations.length === 1) return once(result.definition);return series(operations.slice(1));},},},})

The implementation of the series node. See the series documentation to learn more.

Const SetNodeType

SetNodeType: StatelessNodeType<"set", SetNodeProperties> = createNodeType<'set',SetNodeProperties>('set', {shape: {target: graphTypes.nodeDefinition,value: graphTypes.nodeDefinition,},operations: {evaluate: {cacheable: false,getDependencies({ target }: SetNodeProperties): [NodeDependency] {return [{target,until: untilSupportsSetOperation,},];},run(node: SetNode, operation: never, [targetNode]: [SettableGraphNode]): GraphAction {const { value } = node.definition.properties;return createGraphAction(targetNode, setOperation(value));},},},})

The implementation of the set node. See the set documentation to learn more.

Const SetOperationType

SetOperationType: OperationType<"set", SetProperties> = createOperationType<'set',SetProperties>('set', {cacheable: false,shape: {value: graphTypes.nodeDefinition,},})

An implementation of the setOperation. See the setOperation documentation to find out more.

Const SetResultNodeType

SetResultNodeType: StatelessNodeType<"setResult", SetResultNodeProperties> = createNodeType<'setResult', SetResultNodeProperties>('setResult', {shape: {target: graphTypes.nodeDefinition,value: graphTypes.nodeDefinition,},operations: {evaluate: {cacheable: false,getDependencies({ target, value }: SetResultNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsSetOperation,},{target: value,},];},run(node: SetResultNode,operation: never,[targetNode, value]: [SettableGraphNode, GraphNode],): GraphAction {return createGraphAction(targetNode, setOperation(value.definition));},},},})

The implementation of the setResult node. See the setResult documentation to learn more.

Const ShiftNodeType

ShiftNodeType: StatefulNodeType<"shift", ShiftNodeProperties, ShiftNodeState, __type> = createNodeType<'shift', ShiftNodeProperties, ShiftNodeState, {}>('shift', {shape: {id: types.number,target: graphTypes.nodeDefinition,},state: {currentValue: types.optional(graphTypes.nodeDefinition),},getInitialState() {return {currentValue: undefined,};},operations: {evaluate: {cacheable: false,run(node: ShiftNode,options: never,dependencies: never,context: never,state: ShiftNodeState,): GraphNode {return state.currentValue!;},onSubscribe(this: NodeExecutionContext<ShiftNodeState, {}>, node: ShiftNode): void {if (this.getState().currentValue) return;const { target } = node.definition.properties;this.setState(() => ({currentValue: withScopeFrom(node,resolve([{ target, until: untilSupportsShiftOperation }], ([resolvedTarget]) => {return withScopeFrom(resolvedTarget,resolve([createGraphAction(resolvedTarget, shiftOperation())], ([result]) => {this.setState(() => ({ currentValue: result }));return result;}),);}),),}));},},},})

The implementation of the shift node. See the shift documentation for more information.

Const ShiftOperationType

ShiftOperationType: OperationType<"shift", ShiftProperties> = createOperationType<'shift',ShiftProperties>('shift', {cacheable: false,shape: {},})

An implementation of the shiftOperation. See the shiftOperation documentation to find out more.

Const SkipNodeType

SkipNodeType: StatelessNodeType<"skip", SkipNodeProperties> = createNodeType('skip', {shape: {offset: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ offset }: SkipNodeProperties): Array<NodeDependency> {return [{target: offset,until: untilPositiveIntegerOffset,},];},run(node: SkipNode,operation: TransformItemsOperation,[offset]: [ValueNode<number>],): NodeDefinition {const { value: offsetValue } = offset.definition.properties;return nodeList(operation.properties.items.slice(offsetValue));},},init: {run(node: SkipNode, operation: InitOperation): NodeDefinition {const { next } = operation.properties;if (!next) {return error('Skip reducer cannot be used as a base reducer');}return withReducerState(0, traverse(next, init()));},},step: {getDependencies({ offset }: SkipNodeProperties): Array<NodeDependency> {return [{target: offset,until: untilPositiveIntegerOffset,},];},run(node: SkipNode,operation: StepOperation<[any, number]>,[offset]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const { acc, item, next } = operation.properties;if (!next) {return error('Skip reducer cannot be used as a base reducer');}const [items, currentIndex] = acc;const { value: firstIndex } = offset.definition.properties;if (currentIndex < firstIndex) {return withReducerState(currentIndex + 1, value(items));}return withReducerState(currentIndex, traverse(next, step(items, item)));},},result: {run(node: SkipNode, operation: ResultOperation<[any, number]>): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('Skip reducer cannot be used as a base reducer');}const [items] = acc;return createGraphAction(next, result(items));},},},})

An implementation of the skip node. See the skip documentation to find out more.

Const SliceNodeType

SliceNodeType: StatelessNodeType<"slice", SliceNodeProperties> = createNodeType('slice',{shape: {offset: graphTypes.nodeDefinition,length: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ offset, length }: SliceNodeProperties): Array<NodeDependency> {return [{target: offset,until: untilPositiveIntegerOffset,},{target: length,until: untilPositiveIntegerLength,},];},run(node: SliceNode,operation: TransformItemsOperation,[offset, length]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const { items } = operation.properties;const { value: offsetValue } = offset.definition.properties;const { value: lengthValue } = length.definition.properties;return nodeList(items.slice(offsetValue, offsetValue + lengthValue));},},init: {run(node: SliceNode, operation: InitOperation): NodeDefinition {const { next } = operation.properties;if (!next) {return error('Slice reducer cannot be used as a base reducer');}return withReducerState(0, traverse(next, init()));},},step: {getDependencies({ offset, length }: SliceNodeProperties): Array<NodeDependency> {return [{target: offset,until: untilPositiveIntegerOffset,},{target: length,until: untilPositiveIntegerLength,},];},run(node: SliceNode,operation: StepOperation<[any, number]>,[offset, length]: [ValueNode<number>, ValueNode<number>],): NodeDefinition {const { acc, item, next } = operation.properties;if (!next) {return error('Slice reducer cannot be used as a base reducer');}const [items, currentIndex] = acc;const firstIndex = offset.definition.properties.value;const lastIndex = firstIndex + length.definition.properties.value - 1;if (currentIndex < firstIndex) {return withReducerState(currentIndex + 1, value(items));}if (currentIndex > lastIndex) {return done(withReducerState(currentIndex + 1, value(items)));}const nextValue = withReducerState(currentIndex + 1, traverse(next, step(items, item)));return currentIndex === lastIndex ? done(nextValue) : nextValue;},},result: {run(node: SliceNode,operation: ResultOperation<[any, number]>,): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('Slice reducer cannot be used as a base reducer');}const [items] = acc;return createGraphAction(next, result(items));},},},},)

The implementation of the slice node. See the slice documentation to learn more.

Const SortNodeType

SortNodeType: StatelessNodeType<"sort", SortNodeProperties> = createNodeType('sort', {shape: {order: types.arrayOf(graphTypes.nodeDefinition),},operations: {transformItems: {getDependencies({ order }: SortNodeProperties): Array<NodeDependency> {return order.map((item) => ({target: item,until: untilIsSortOrderNode,}));},run(node: SortNode,operation: TransformItemsOperation,orderNodes: Array<SortOrderNode>,): NodeDefinition {const { items } = operation.properties;const descending = orderNodes.map((orderNode) => orderNode.definition.properties.descending,);return resolve(flatMap(items, (item) =>orderNodes.map((order) => ({target: apply([item], order),until: untilIsValidSortValue,})),),(combinedSortValueNodes: Array<ValueNode<SortValue>>) => {const combinedSortValues = combinedSortValueNodes.map((node) => node.definition.properties.value,);const itemSortValues = chunk(combinedSortValues, orderNodes.length);const sortedItems = (zip<GraphNode | Array<SortValue>>(items, itemSortValues) as Array<[GraphNode, Array<SortValue>]>).sort(([item1, sortValues1], [item2, sortValues2]) =>compareSortValues(sortValues1, sortValues2, descending),).map(([item]) => item);return withScopeFrom(node, nodeList(sortedItems));},);},},init: {run(node: SortNode): NodeDefinition {const initialState = [] as Array<GraphNode>;return value(initialState);},},step: {run(node: SortNode, operation: StepOperation<Array<GraphNode>>): NodeDefinition {const { acc, item } = operation.properties;return value([...acc, item]);},},result: {getDependencies({ order }: SortNodeProperties): Array<NodeDependency> {return order.map((iteratee) => ({target: iteratee,until: untilIsSortOrderNode,}));},run(node: SortNode,operation: ResultOperation<Array<GraphNode>>,orderNodes: Array<SortOrderNode>,): NodeDefinition {const { acc, next } = operation.properties;if (!next) {return error('Sort reducer cannot be used as a base reducer');}const descending = orderNodes.map((orderNode) => orderNode.definition.properties.descending,);const sortedItems = resolve(flatMap(acc, (item) =>orderNodes.map((order) => ({target: apply([item], order.definition.properties.iteratee),until: untilIsValueNode,})),),(orderResults: Array<ValueNode<SortValue>>) => {const itemsWithSortValues = acc.map((item, itemIndex) =>[item,orderNodes.map((order, orderIndex) =>orderResults[itemIndex * orderNodes.length + orderIndex].definition.properties.value,),] as [GraphNode, Array<SortValue>],);const sortedItems = itemsWithSortValues.sort(([, sortValues1], [, sortValues2]) => {return compareSortValues(sortValues1, sortValues2, descending);}).map(([item]) => item);return withScopeFrom(node, nodeList(sortedItems));},);return value(transduce(sortedItems, [next]));},},},})

The implementation of the sort node. See the sort documentation to learn more.

Const SortOrderNodeType

SortOrderNodeType: StatelessNodeType<"sortOrder", SortOrderNodeProperties> = createNodeType('sortOrder', {shape: {iteratee: graphTypes.nodeDefinition,descending: types.bool,},operations: {call: {getDependencies({ iteratee }: SortOrderNodeProperties,operation: CallOperation,): Array<NodeDependency> {return [{target: apply(operation.properties.args!, iteratee),until: untilIsValidSortValue,},];},run(node: SortOrderNode, operation: CallOperation, [result]: [GraphNode]): GraphNode {return result;},},},})

Const SplitNodeType

SplitNodeType: StatelessNodeType<"split", SplitNodeProperties> = createNodeType<'split',SplitNodeProperties>('split', {shape: {limit: types.optional(graphTypes.nodeDefinition),separator: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ limit, separator, subject }: SplitNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(SplitNodeType, 'subject'),},{target: separator,until: untilStringValueNode(SplitNodeType, 'separator'),},...(limit? [{ target: limit, until: untilPositiveIntegerValueNode(SplitNodeType, 'limit') }]: []),];},run(node: SplitNode,options: never,[subject, separator, ...rest]: [ValueNode<string>, ValueNode<string>, ValueNode<number>],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const separatorValue = separator.definition.properties.value;const limitValue =rest.length === 1 ? (rest[0].definition.properties.value as number) : undefined;return array(subjectValue.split(separatorValue, limitValue).map(value));},},},})

The implementation of the split node. See the split documentation to learn more.

Const SqrtNodeType

SqrtNodeType: StatelessNodeType<"sqrt", SqrtNodeProperties> = createNodeType<'sqrt',SqrtNodeProperties>('sqrt', {shape: {operand: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ operand }: SqrtNodeProperties): Array<NodeDependency> {return [{target: operand,until: untilNumberValueNode(SqrtNodeType, 'base'),},];},run(node: SqrtNode, options: never, [operand]: [ValueNode<number>]): NodeDefinition {return value(Math.sqrt(operand.definition.properties.value));},},},})

The implementation of the sqrt node. See the sqrt documentation to learn more.

Const StartCaseNodeType

StartCaseNodeType: StatelessNodeType<"start-case", StartCaseNodeProperties> = createNodeType<'start-case', StartCaseNodeProperties>('start-case', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: StartCaseNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(StartCaseNodeType, 'subject'),},];},run(node: StartCaseNode, options: never, [subject]: [ValueNode<string>]): NodeDefinition {if (NilNodeType.is(subject)) return nil();return value(lodashStartCase(subject.definition.properties.value));},},},})

The implementation of the startCase node. See the startCase documentation to learn more.

Const StartsWithNodeType

StartsWithNodeType: StatelessNodeType<"starts-with", StartsWithNodeProperties> = createNodeType<'starts-with', StartsWithNodeProperties>('starts-with', {shape: {pattern: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ pattern, subject }: StartsWithNodeProperties): Array<NodeDependency> {return [{target: pattern,until: untilStringValueNode(StartsWithNodeType, 'pattern'),},{target: subject,acceptNil: true,until: untilStringValueNode(StartsWithNodeType, 'subject'),},];},run(node: StartsWithNode,options: never,[pattern, subject]: [ValueNode<string>, ValueNode<string>],): NodeDefinition {if (NilNodeType.is(subject)) return value(false);const patternValue = pattern.definition.properties.value;const subjectValue = subject.definition.properties.value;return value((subjectValue || '').startsWith(patternValue));},},},})

The implementation of the startsWith node. See the startsWith documentation to learn more.

Const StepOperationType

StepOperationType: OperationType<"step", StepProperties<any>> = createOperationType<'step',StepProperties<any>>('step', {shape: {acc: types.optional(types.saveHash(types.any)),item: graphTypes.graphNode,next: types.optional(graphTypes.graphNode),},})

An implementation of the [[stepOperation]]. See the [[stepOperation]] documentation to find out more.

Const StringNodeTypes

StringNodeTypes: Array<NodeType> = [CharAtNodeType,EndsWithNodeType,FormatNodeType,FromBase64NodeType,IncludesNodeType,JoinNodeType,LowerCaseNodeType,MatchPatternNodeType,ParseFloatNodeType,ParseIntNodeType,RegexNodeType,ReplaceNodeType,SentenceCaseNodeType,SplitNodeType,StartCaseNodeType,StartsWithNodeType,SubstringNodeType,TestNodeType,ToBase64NodeType,ToStringNodeType,TrimNodeType,TruncateNodeType,UpperCaseNodeType,]

Const SubstringNodeType

SubstringNodeType: StatelessNodeType<"substring", SubstringNodeProperties> = createNodeType<'substring', SubstringNodeProperties>('substring', {shape: {endIndex: types.optional(graphTypes.nodeDefinition),startIndex: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({endIndex,startIndex,subject,}: SubstringNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(SubstringNodeType, 'subject'),},{target: startIndex,until: untilPositiveIntegerValueNode(SubstringNodeType, 'startIndex'),},...(endIndex? [{target: endIndex,until: untilPositiveIntegerValueNode(SubstringNodeType, 'endIndex'),},]: []),];},run(node: SubstringNode,options: never,[subject, startIndex, endIndex]: [ValueNode<string>, ValueNode<number>, ValueNode<number>],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const startIndexValue = startIndex.definition.properties.value;const endIndexValue = endIndex ? endIndex.definition.properties.value : undefined;if (startIndexValue > subjectValue.length) return value('');return value(subjectValue.substring(startIndexValue, endIndexValue));},},},})

The implementation of the substring node. See the substring documentation to learn more.

Const SubtractNodeType

SubtractNodeType: StatelessNodeType<"subtract", SubtractNodeProperties> = createNodeType<'subtract', SubtractNodeProperties>('subtract', {shape: {operands: types.arrayOf(graphTypes.nodeDefinition),},operations: {evaluate: {getDependencies({ operands }: SubtractNodeProperties): Array<NodeDependency> {return operands.map((operand) => ({target: operand,until: untilNumberValueNode(SubtractNodeType, 'operand'),}));},run(node: SubtractNode, options: never, operands: Array<ValueNode<number>>): NodeDefinition {assertEnoughOperands(operands);const operandValues = operands.map((operand) => operand.definition.properties.value);return value(operandValues.reduce((total, value) => total - value));},},},})

The implementation of the subtract node. See the subtract documentation to learn more.

Const SwitchOnNodeType

SwitchOnNodeType: StatelessNodeType<"switchOn", SwitchOnNodeProperties> = createNodeType<'switchOn', SwitchOnNodeProperties>('switchOn', {shape: {input: graphTypes.nodeDefinition,options: types.arrayOf(graphTypes.nodeDefinition),fallback: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ input, options }: SwitchOnNodeProperties): Array<NodeDependency> {return [{target: input,until: untilInputIsValueNode,},...options.map((option) => ({target: option.properties.pattern,until: untilPatternIsValueNodeOrCallableNode,})),];},run(node: SwitchOnNode,operation: never,dependencies: Array<ValueNode<any> | CallableGraphNode>,): NodeDefinition {const { options, fallback } = node.definition.properties;const [input] = dependencies as [ValueNode<any>];const [, ...resolvedOptions] = dependencies;return choose([...resolvedOptions.map((option, index) =>when(ValueNodeType.is(option)? eq(input.definition, option.definition): apply([input], option),options[index].properties.value,),),fallback,]);},},},})

The implementation of the switchOn node. See the switchOn documentation to learn more.

Const TRANSACTION_END

TRANSACTION_END: "$$event:transactionEnd" = "$$event:transactionEnd"

Const TRANSACTION_START

TRANSACTION_START: "$$event:transactionStart" = "$$event:transactionStart"

Const TYPE_HASHERS

TYPE_HASHERS: Map<Matcher<any, any> | function, HashFunction<any> | ValueHasherFactory<any, any>> = new Map<Matcher<any, any> | ((options: any) => Matcher<any, any>),HashFunction<any> | ValueHasherFactory<any, any>>([[types.empty, empty],[types.nil, nil],[types.bool, bool],[types.number, number],[types.integer, number],[types.string, string],[types.symbol, symbol],[types.date, date],[types.func, func],[types.object, object],[types.matcher, matcher],[types.instance, instance],[types.array, array],[types.instanceOf, instanceOf],[types.any, any],[types.oneOf, oneOf],[types.shape, shape],[types.arrayOf, arrayOf],[types.objectOf, objectOf],[types.oneOfType, oneOfType],[types.ignore, ignore],[types.optional, optional],[types.saveHash, saveHash],])

Const TakeLastNodeType

TakeLastNodeType: StatefulNodeType<"takeLast", TakeLastNodeProperties, TakeLastNodeState, TakeLastNodeData> = createNodeType<'takeLast', TakeLastNodeProperties, TakeLastNodeState, TakeLastNodeData>('takeLast',{state: {},shape: {operations: types.arrayOf(graphTypes.nodeDefinition),},getInitialState(): TakeLastNodeState {return {};},operations: {evaluate: {run(node: TakeLastNode): NodeDefinition {return last(node.definition.properties.operations) || nil();},onSubscribe(this: NodeExecutionContext<TakeLastNodeState, TakeLastNodeData>,node: TakeLastNode,): void {const { operations } = node.definition.properties;const subscriptions = operations.slice(0, -1).map((operation) =>node.scope.store.subscribe(withScopeFrom(node, operation), resolveOperation(), noop),);this.setData({unsubscribe: () => subscriptions.forEach((unsubscribe) => unsubscribe()),});},onUnsubscribe(this: NodeExecutionContext<TakeLastNodeState, TakeLastNodeData>): void {const { unsubscribe } = this.getData();if (unsubscribe) {unsubscribe();}},},},},)

The implementation of the takeLast node. See the takeLast documentation to learn more.

Const TakeNodeType

TakeNodeType: StatelessNodeType<"take", TakeNodeProperties> = createNodeType('take', {shape: {numItems: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ numItems }: TakeNodeProperties): Array<NodeDependency> {return [{target: numItems,until: untilPositiveNumItemsNode,},];},run(node: TakeNode,operation: TransformItemsOperation,[numItems]: [ValueNode<number>],): NodeDefinition {const { value: numItemsValue } = numItems.definition.properties;return nodeList(operation.properties.items.slice(0, numItemsValue));},},init: {run(node: TakeNode, operation: InitOperation): NodeDefinition {const { next } = operation.properties;if (!next) {return error('Take reducer cannot be used as a base reducer');}return withReducerState(0, traverse(next, init()));},},step: {getDependencies({ numItems }: TakeNodeProperties): Array<NodeDependency> {return [{target: numItems,until: untilPositiveNumItemsNode,},];},run(node: TakeNode,operation: StepOperation<[any, number]>,[numItems]: [ValueNode<number>],): NodeDefinition {const { acc, item, next } = operation.properties;if (!next) {return error('Take reducer cannot be used as a base reducer');}const [items, currentIndex] = acc;const lastIndex = numItems.definition.properties.value - 1;if (currentIndex > lastIndex) {return done(value(acc));}const nextValue = withReducerState(currentIndex + 1, traverse(next, step(items, item)));return currentIndex === lastIndex ? done(nextValue) : nextValue;},},result: {run(node: TakeNode, operation: ResultOperation<[any, number]>): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('Take reducer cannot be used as a base reducer');}const [items] = acc;return createGraphAction(next, result(items));},},},})

The implementation of the take node. See the take documentation to learn more.

Const TestNodeType

TestNodeType: StatelessNodeType<"test", TestNodeProperties> = createNodeType<'test',TestNodeProperties>('test', {shape: {regex: graphTypes.nodeDefinition,subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ regex, subject }: TestNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(TestNodeType, 'subject'),},{target: regex,until: untilRegexNode(TestNodeType, 'regex'),},];},run(node: TestNode,options: never,[subject, regex]: [ValueNode<string>, RegexNode],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const regexValue = regex.definition.properties.pattern;return value(regexValue.test(subjectValue));},},},})

The implementation of the test node. See the test documentation to learn more.

Const ToBase64NodeType

ToBase64NodeType: StatelessNodeType<"to-base64", ToBase64NodeProperties> = createNodeType<'to-base64', ToBase64NodeProperties>('to-base64', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: ToBase64NodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(ToBase64NodeType, 'subject'),},];},run(node: ToBase64Node, options: never, [subject]: [ValueNode<string>]): NodeDefinition {if (NilNodeType.is(subject)) return nil();return value(btoa(subject.definition.properties.value));},},},})

The implementation of the toBase64 node. See the toBase64 documentation to learn more.

Const ToStringNodeType

ToStringNodeType: StatelessNodeType<"to-string", ToStringNodeProperties> = createNodeType<'to-string', ToStringNodeProperties>('to-string', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: ToStringNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilValueNode(ToStringNodeType, 'subject'),},];},run(node: ToStringNode, options: never, [subject]: [ValueNode<any>]): NodeDefinition {if (NilNodeType.is(subject)) return nil();return value(lodashToString(subject.definition.properties.value));},},},})

The implementation of the toString node. See the toString documentation to learn more.

Const TransduceNodeType

TransduceNodeType: StatelessNodeType<"transduce", TransduceNodeProperties> = createNodeType<'transduce', TransduceNodeProperties>('transduce', {shape: {source: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),reducer: types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode]),},operations: {evaluate: {getDependencies({ reducer }: TransduceNodeProperties): Array<NodeDependency> {return [{target: traverse(reducer, init()),until: untilValidInitializer,},];},run(node: TransduceNode, options: never, [initialState]: [ValueNode<any>]): NodeDefinition {const { source, reducer } = node.definition.properties;return resolve([{target: reduce(source, reducer, initialState.definition.properties.value),until: untilValidStepResult,},],([acc]: [ValueNode<any>]) =>withScopeFrom(acc,resolve([{target: traverse(reducer, result(acc.definition.properties.value)),until: untilValidResult,},],([finalValue]: [ValueNode<any>]) => finalValue.definition.properties.value,),),);},},},})

Const TransformItemsOperationType

TransformItemsOperationType: OperationType<"transformItems", TransformItemsProperties> = createOperationType<'transformItems', TransformItemsProperties>('transformItems', {shape: {items: types.arrayOf(graphTypes.graphNode),},})

An implementation of the [[transformItemsOperation]]. See the [[transformItemsOperation]] documentation to find out more.

Const TransformResponseMiddlewareNodeType

TransformResponseMiddlewareNodeType: StatelessNodeType<"transform-response-middleware", TransformResponseMiddlewareNodeProperties> = createNodeType('transform-response-middleware', {shape: {responseTransformer: types.saveHash(types.func),},operations: {request: {run(node: TransformResponseMiddlewareNode, operation: RequestOperation): NodeDefinition {const { metadata, next, query } = operation.properties;if (!next) {return error('TransformResponseMiddleware cannot be used as a base middleware.');}const { responseTransformer } = node.definition.properties;return resolve([{target: withScopeFrom(next,traverse(next.definition, requestOperation(query, metadata)),),allowErrors: true,},],([response]) => withScopeFrom(response, responseTransformer(response.definition)),);},},},})

Const TransformsNodeTypes

TransformsNodeTypes: Array<NodeType> = [CountNodeType,FilterNodeType,FirstItemNodeType,LastItemNodeType,MapNodeType,NthItemNodeType,SkipNodeType,SliceNodeType,SortNodeType,SortOrderNodeType,TakeNodeType,UniqueNodeType,]

Const TreeNodeType

TreeNodeType: StatelessNodeType<"tree", TreeNodeProperties, SerializedTreeNodeProperties> = createNodeType<'tree', TreeNodeProperties, SerializedTreeNodeProperties>('tree', {shape: {branches: types.arrayOf(types.shape({match: types.saveHash(types.any),param: types.optional(types.string),node: graphTypes.nodeDefinition,}),),},operations: {getChild: {run(node: TreeNode, operation: GetChildOperation): NodeDefinition | GraphNode {const { key } = operation.properties;const branches = node.definition.properties.branches;const matchingBranch = findBranchByKey(branches, key);if (!matchingBranch) {return notFound(`Invalid child key: ${getType(key)}`);}const { param, node: child } = matchingBranch;const childContext = createChildPathContext(node,key,param === undefined? undefined: {[getParamContextId(param)]: withScopeFrom(node, value(key)),},);return createGraphNode(node.scope, childContext, child);},},},serialize<T>(properties: TreeNodeProperties,serialize: (value: any) => any,): SerializedTreeNodeProperties<T> {const { branches } = properties;return {branches: branches.map((b) => ({match: b.param === MISSING_PARAM_NAME ? undefined : serialize(b.match),param: b.param,node: serialize(b.node),})),};},deserialize<T>(data: SerializedTreeNodeProperties<T>,deserialize: (value: any) => any,): TreeNodeProperties {return {branches: data.branches.map((b) => {const deserializedNode = deserialize(b.node);if (b.param === MISSING_PARAM_NAME) {return { param: MISSING_PARAM_NAME, node: deserializedNode, match: types.any };}return { param: b.param, node: deserializedNode, match: deserialize(b.match) };}),};},getType(properties: TreeNodeProperties, getType: (value: any) => string): string {return `${TreeNodeType.name}({ ${(properties.branches as Array<any>).map((branch) =>`${typeof branch.match === 'string'? branch.match: branch.match.name? `[${branch.match.name}]`: '*'}: ${getType(branch.node)}`,).join(', ')} })`;},})

The implementation of the tree node. See the tree documentation to learn more.

Const TrimNodeType

TrimNodeType: StatelessNodeType<"trim", TrimNodeProperties> = createNodeType<'trim',TrimNodeProperties>('trim', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: TrimNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(TrimNodeType, 'subject'),},];},run(node: TrimNode, options: never, [subject]: [ValueNode<string>]): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;return value((subjectValue || '').trim());},},},})

The implementation of the trim node. See the trim documentation to learn more.

Const TruncateNodeType

TruncateNodeType: StatelessNodeType<"truncate", TruncateNodeProperties> = createNodeType<'truncate', TruncateNodeProperties>('truncate', {shape: {length: graphTypes.nodeDefinition,omission: types.optional(graphTypes.nodeDefinition),subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({length,omission,subject,}: TruncateNodeProperties): Array<NodeDependency> {return [{target: subject,acceptNil: true,until: untilStringValueNode(TruncateNodeType, 'subject'),},{target: length,until: untilPositiveIntegerValueNode(TruncateNodeType, 'length'),},...(omission? [{target: omission,until: untilStringValueNode(TruncateNodeType, 'omission'),},]: []),];},run(node: TruncateNode,options: never,[subject, length, omission]: [ValueNode<string>, ValueNode<number>, ValueNode<string>],): NodeDefinition {if (NilNodeType.is(subject)) return nil();const subjectValue = subject.definition.properties.value;const lengthValue = length.definition.properties.value;const omissionValue = omission ? omission.definition.properties.value : '…';return value(lodashTruncate(subjectValue, {length: lengthValue,omission: omissionValue,}),);},},},})

The implementation of the truncate node. See the truncate documentation to learn more.

Const UniqueNodeType

UniqueNodeType: StatelessNodeType<"unique", UniqueNodeProperties> = createNodeType('unique',{shape: {predicate: graphTypes.nodeDefinition,},operations: {transformItems: {getDependencies({ predicate }: UniqueNodeProperties,operation: TransformItemsOperation,): Array<NodeDependency> {return operation.properties.items.map((item) => ({target: apply([item], predicate),until: untilIsValueNode,}));},run(node: UniqueNode,operation: TransformItemsOperation,uniqueResults: Array<ValueNode<any>>,): NodeDefinition {const { items } = operation.properties;const uniqueValues = uniqBy(uniqueResults.map((item, index) => [index, item] as [number, ValueNode<any>]),([index, item]) => valueOf(item),);return nodeList(uniqueValues.map(([index]) => items[index]));},},init: {run(node: UniqueNode, operation: InitOperation): NodeDefinition | GraphAction {const { next } = operation.properties;if (!next) {return error('Unique reducer cannot be used as a base reducer');}return createGraphAction(next, init());},},step: {run(node: UniqueNode, operation: StepOperation<Array<GraphNode>>): NodeDefinition {const { acc, item } = operation.properties;return value([...acc, item]);},},result: {run(node: UniqueNode, operation: ResultOperation<any>): NodeDefinition | GraphAction {const { acc, next } = operation.properties;if (!next) {return error('Unique reducer cannot be used as a base reducer');}const uniqueItems = resolve(acc.map((item: GraphNode) => ({target: apply([item], node.definition.properties.predicate),until: untilIsValueNode,})),(predicateResults: Array<ValueNode<any>>) => {const uniqueValues = uniqBy(predicateResults.map((item, index) => [index, item] as [number, ValueNode<any>]),([index, item]) => valueOf(item),);return nodeList(uniqueValues.map(([index]) => acc[index]));},);return value(transduce(uniqueItems, [next]));},},},},)

The implementation of the unique node. See the unique documentation to learn more.

Const UnshiftNodeType

UnshiftNodeType: StatefulNodeType<"unshift", UnshiftNodeProperties, UnshiftNodeState, __type> = createNodeType<'unshift', UnshiftNodeProperties, UnshiftNodeState, {}>('unshift', {shape: {item: graphTypes.nodeDefinition,target: graphTypes.nodeDefinition,},state: {memoized: types.saveHash(types.func),},getInitialState() {return {memoized: once((target: GraphNode, item: NodeDefinition) =>createGraphAction(target, unshiftOperation(item)),),};},operations: {evaluate: {cacheable: false,getDependencies({ target }: UnshiftNodeProperties): Array<NodeDependency> {return [{target,until: untilSupportsUnshiftOperation,},];},run(node: UnshiftNode,options: never,[target]: [GraphNode],context: never,state: UnshiftNodeState,): GraphAction {return state.memoized(target, node.definition.properties.item);},},},})

The implementation of the unshift. See the unshift documentation for more information.

Const UnshiftOperationType

UnshiftOperationType: OperationType<"unshift", UnshiftProperties> = createOperationType<'unshift', UnshiftProperties>('unshift', {cacheable: false,shape: {value: graphTypes.nodeDefinition,},})

An implementation of the unshiftOperation. See the unshiftOperation documentation to find out more.

Const UpdateNodeType

UpdateNodeType: StatelessNodeType<"update", UpdateNodeProperties> = createNodeType<'update',UpdateNodeProperties>('update', {shape: {target: graphTypes.nodeDefinition,updater: graphTypes.nodeDefinition,},operations: {evaluate: {cacheable: false,getDependencies({ target, updater }: UpdateNodeProperties): [NodeDependency] {return [{target: call(updater, [target]),},];},run(node: UpdateNode, operation: never, [newValueNode]: [GraphNode]): NodeDefinition {return set(node.definition.properties.target, newValueNode.definition);},},},})

The implementation of the update node. See the update documentation to learn more.

Const UpperCaseNodeType

UpperCaseNodeType: StatelessNodeType<"upper-case", UpperCaseNodeProperties> = createNodeType<'upper-case', UpperCaseNodeProperties>('upper-case', {shape: {subject: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ subject }: UpperCaseNodeProperties): Array<NodeDependency> {return [{target: subject,until: untilStringValueNode(UpperCaseNodeType, 'subject'),},];},run(node: UpperCaseNode, options: never, [subject]: [ValueNode<string>]): NodeDefinition {return value(subject.definition.properties.value.toUpperCase());},},},})

The implementation of the upperCase node. See the upperCase documentation to learn more.

Const ValueNodeType

ValueNodeType: StaticNodeType<"value", ValueNodeProperties<any>> = createNodeType<'value',ValueNodeProperties<any>>('value', {shape: {value: types.optional(types.saveHash(types.any)),},operations: {length: {run(node: ValueNode<any>): NodeDefinition {const { value: currentValue } = node.definition.properties;if (typeof currentValue === 'string') return value(currentValue.length);if (Array.isArray(currentValue)) return value(currentValue.length);return error('This value node does not support the length operation.');},},},})

The implementation of the value node. See the value documentation to learn more.

Const VariableNodeType

VariableNodeType: StatefulNodeType<"variable", VariableNodeProperties, VariableNodeState, VariableNodeData> = createNodeType<'variable', VariableNodeProperties, VariableNodeState, VariableNodeData>('variable',{state: {currentValue: types.optional(graphTypes.nodeDefinition),setResults: types.objectOf(graphTypes.nodeDefinition),},shape: {initialValue: graphTypes.nodeDefinition,validator: types.saveHash(types.matcher),},getInitialState(): VariableNodeState {return {currentValue: undefined,setResults: {},};},operations: {evaluate: {run(node: VariableNode,operation: never,dependencies: Array<never>,context: Array<never>,state: VariableNodeState,): NodeDefinition {const { currentValue } = state;return currentValue || node.definition.properties.initialValue;},},set: {run(node: VariableNode,operation: SetOperation,dependencies: never,context: never,state: VariableNodeState,): NodeDefinition {return state.setResults[operation.id];},onSubscribe(this: NodeExecutionContext<VariableNodeState, VariableNodeData>,node: VariableNode,operation: SetOperation,): void {const { currentValue: previousValue } = this.getState();const { validator } = node.definition.properties;const { value } = operation.properties;if (!previousValue) {this.retain();this.setData({disposeResetVariableListener: node.scope.events.listen((event) => {if (event.type !== EVENT_RESET_VARIABLE) return;resetVariableNode(this);}),});}// Check if the value is validif (isValueNodeDefinition(value) ? validator(valueOf(value)) : validator(value)) {// All is good in variable worldthis.setState((state) => ({...state,currentValue: value,setResults: {...state.setResults,[operation.id]: ok(),},}));} else {// Whoops, wrong value type!this.setState((state) => ({...state,setResults: {...state.setResults,[operation.id]: error(getInvalidTypeError('Could not set value of the variable node: value has an incorrect type.',{expected: `Value matched by ${getType(validator)}`,received: value,},),),},}));}},onUnsubscribe(this: NodeExecutionContext<VariableNodeState, VariableNodeData>,node: VariableNode,operation: SetOperation,): void {this.setState((state) => ({...state,setResults: omit(state.setResults, operation.id),}));},},reset: {run(node: VariableNode,options: never,dependencies: Array<never>,context: Array<never>,state: VariableNodeState,): NodeDefinition {return ok();},onSubscribe(this: NodeExecutionContext<VariableNodeState, VariableNodeData>,node: VariableNode,): void {resetVariableNode(this);},},},},)

The implementation of the variable node. See the variable documentation to learn more.

Const WILDCARD_OPERATION

WILDCARD_OPERATION: "$$WILDCARD_OPERATION" = "$$WILDCARD_OPERATION"

Const WhenNodeType

WhenNodeType: StaticNodeType<"when", WhenNodeProperties> = createNodeType<'when',WhenNodeProperties>('when', {shape: {pattern: graphTypes.nodeDefinition,value: graphTypes.nodeDefinition,},})

The implementation of the when node. See the when documentation to learn more.

Const WithContextNodeType

WithContextNodeType: StatelessNodeType<"withContext", WithContextNodeProperties> = createNodeType<'withContext', WithContextNodeProperties>('withContext', {shape: {values: types.objectOf(types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),),target: graphTypes.nodeDefinition,},operations: {evaluate: {run(node: WithContextNode): GraphNode {const { target, values } = node.definition.properties;const boundContextValues = fromPairs([...Object.getOwnPropertySymbols(values), ...Object.keys(values)].map((contextKey): [string | symbol, GraphNode] => {// TODO: Remove the `as any` cast once https://github.com/Microsoft/TypeScript/issues/1863 is resolvedconst value = values[contextKey as any];return [contextKey, isGraphNode(value) ? value : withScopeFrom(node, value)];},),);const childContext = createContext(node.context, boundContextValues);return createGraphNode(node.scope, childContext, target);},},},})

The implementation of the withContext node. See the withContext documentation to learn more.

Const WithScopeNodeType

WithScopeNodeType: StatelessNodeType<"withScope", WithScopeNodeProperties> = createNodeType<'withScope', WithScopeNodeProperties>('withScope', {shape: {target: types.oneOfType<NodeDefinition | GraphNode>([graphTypes.nodeDefinition,graphTypes.graphNode,]),expression: graphTypes.nodeDefinition,},operations: {evaluate: {getDependencies({ target, expression }: WithScopeNodeProperties): [NodeDependency] {return [{ target }];},run(node: WithScopeNode, options: never, [subjectNode]: [GraphNode]): GraphNode {const { expression } = node.definition.properties;return withScopeFrom(subjectNode, expression);},},},})

The implementation of the withScope node. See the withScope documentation for more information.

Const WithTransformsNodeType

WithTransformsNodeType: StaticNodeType<"withTransforms", WithTransformsNodeProperties> = createNodeType<'withTransforms', WithTransformsNodeProperties>('withTransforms', {shape: {transforms: types.arrayOf(graphTypes.nodeDefinition),fields: graphTypes.nodeDefinition,},})

Const XhrMiddlewareNodeType

XhrMiddlewareNodeType: StatelessNodeType<"xhr-middleware", XhrMiddlewareNodeProperties> = createNodeType('xhr-middleware', {shape: {headers: types.optional(graphTypes.nodeDefinition),log: types.bool,nodeTypes: types.saveHash(types.any),numberOfRetries: types.number,operationTypes: types.saveHash(types.any),requestTimeout: types.number,retryDelay: types.number,url: types.string,withCredentials: types.bool,},operations: {request: {run(node: XhrMiddlewareNode, operation: RequestOperation): NodeDefinition | GraphNode {const { query } = operation.properties;const options = node.definition.properties;const processRequest = (headersNode?: NodeDefinition): GraphNode => {if (options.log) {console.log(`Request [${operation.id}] headers:`, getType(headersNode));}const headersObject = {Accept: 'application/json, text/plain, */*','Content-Type': 'application/json',...(getCustomHeaders(headersNode) || {}),};const requestStream = doHttpRequest({body: JSON.stringify(attachMetadata(sanitize(query))),headers: headersObject,numberOfRetries: options.numberOfRetries,retryDelay: options.retryDelay,requestTimeout: options.requestTimeout,url: options.url,withCredentials: options.withCredentials,});const responseStream = map((response) => deserializeResponse(options.nodeTypes, options.operationTypes, response),requestStream,);return withScopeFrom(node, fromStream(responseStream));};if (!options.headers) return processRequest();return resolve([{ target: options.headers, once: true }], ([resolvedHeaders]) =>processRequest(resolvedHeaders.definition),);},},},})

Const any

any: Matcher<any, never> = createMatcher<any, never>('any', (value: any) => true)

Const array

array: Matcher<any[], never> = createMatcher<Array<any>, never>('array', Array.isArray)

Const array

array: HashFunction<any[]> = unique as HashFunction<Array<any>>

Const arrayOf

arrayOf: ValueHasherFactory<Object[], Matcher<Object, any>> = (<T>() =>createHasherFactory('arrayOf',(matcher: Matcher<T, any>): HashFunction<Array<T>> => {const itemHasher = type(matcher);return (value: Array<T>): string => {let hash = 't(';// tslint:disable-next-line:no-increment-decrementfor (let i = 0; i < value.length; i++) {hash += `${itemHasher(value[i])}|`;}return `${hash})`;};},))()

Const bool

bool: Matcher<boolean, never> = createMatcher<boolean, never>('bool',(value: any) => typeof value === 'boolean',)

Let cachedActionId

cachedActionId: number = 0

Const context

context: HashFunction<Context> = hash.registerTypeHasher(graphTypes.context,(value: Context) => value.id,)

Const context

context: Matcher<Context> = createMatcher('context', isContext)

Const date

date: Matcher<Date, never> = createMatcher<Date, never>('date', (value: any) =>Boolean(value && value.constructor === Date),)

Const empty

empty: Matcher<undefined, never> = createMatcher<undefined, never>('empty',(value: any) => typeof value === 'undefined',)

Const es6TemplateStrings

es6TemplateStrings: any = require('es6-template-strings')

Const event

event: Matcher<MusterEvent> = createMatcher('event', isEvent)

Const event

event: HashFunction<MusterEvent> = hash.registerTypeHasher(graphTypes.event,(value: MusterEvent): string => `${hash.string(value.type)}:${hash.any(value.payload)}`,)

Const func

func: HashFunction<Function> = unique as HashFunction<Function>

Const func

func: Matcher<Function, never> = createMatcher<Function, never>('func',(value: any) => typeof value === 'function',)

Const global

global: Window & object

Const graphAction

graphAction: HashFunction<GraphAction> = hash.registerTypeHasher(graphTypes.graphAction,(value: GraphAction): string => value.id,)

Const graphAction

graphAction: Matcher<GraphAction> = createMatcher('graphAction', isGraphAction)

Const graphDeprecationWarning

graphDeprecationWarning: function = deprecated({old: 'graph',new: 'toNode',})

Type declaration

    • (): void
    • Returns void

Const graphHash

graphHash: "/Users/wragdav/db-projects/muster/packages/muster/src/utils/graph-hash" = _graphHash

Const graphNode

graphNode: Matcher<GraphNode> = createMatcher('graphNode', isGraphNode)

Const graphNode

graphNode: HashFunction<GraphNode> = hash.registerTypeHasher(graphTypes.graphNode,(value: GraphNode): string => value.id,)

Const graphOperation

graphOperation: Matcher<GraphOperation> = createMatcher('graphOperation',isGraphOperation,)

Const graphOperation

graphOperation: HashFunction<GraphOperation> = hash.registerTypeHasher(graphTypes.graphOperation,(value: GraphOperation): string => value.id,)

Const graphTypes

graphTypes: "/Users/wragdav/db-projects/muster/packages/muster/src/utils/graph-types" = _graphTypes

Const hash

hash: "/Users/wragdav/db-projects/muster/packages/muster/src/utils/hash" = _hash

Const hashContextValues

hashContextValues: HashFunction<object> = hashObjectOf(graphTypes.graphNode)

Const ignore

ignore: Matcher<any, never> = createMatcher<any, never>('ignore', (value: any) => true)

Let instance

instance: IterateOperation | undefined

Let instance

instance: ResetOperation | undefined

Const instance

instance: HashFunction<object> = unique as HashFunction<object>

Let instance

instance: IdentityOperation | undefined

Let instance

instance: EvaluateOperation | undefined

Const instanceOf

instanceOf: HashFunction<object> = unique as HashFunction<object>

Const integer

integer: Matcher<number, never> = createMatcher<number, never>('integer', Number.isInteger)

Const isPlainObject

isPlainObject: any = require('is-plain-object')

Const matcher

matcher: HashFunction<Matcher<any, any>> = unique as HashFunction<Matcher<any, any>>

Const matcher

matcher: Matcher<Matcher<any, any>, never> = createMatcher<Matcher<any, any>, never>('matcher', (value: any) =>isMatcher(value),)

Const migrator

migrator: Migrator<NodeBefore, NodeAfter> = createMigrator<NodeBefore, NodeAfter>({[DEFAULT]: {downgrade(node, traverse): NodeBefore {return {$type: node.$type,data: traverse(node.data),};},upgrade(node, traverse): NodeAfter {return {$type: node.$type,data: traverse(node.data),};},},'inject-dependencies': {downgrade(node, traverse): NodeBefore {return {$type: 'partial',data: traverse(node.data),};},},items: {upgrade(node, traverse): NodeAfter {if (Array.isArray(node.data.transforms) && node.data.transforms.length > 0) {return {$type: 'withTransforms',data: {transforms: traverse(node.data.transforms),fields: {$type: 'entries',data: {children: traverse(node.data.children),},},},};}return {$type: 'entries',data: {children: traverse(node.data.children),},};},},entries: {downgrade(node, traverse): NodeBefore {return {$type: 'items',data: {transforms: undefined,children: traverse(node.data.children),},};},},withTransforms: {downgrade(node, traverse): NodeBefore {return {$type: 'items',data: {transforms: traverse(node.data.transforms),children: traverse((node.data.fields as NodeAfter).data.children),},};},},partial: {upgrade(node, traverse): NodeAfter {return {$type: 'inject-dependencies',data: traverse(node.data),};},},takeFirst: {upgrade(node, traverse): NodeAfter {return {$type: 'firstItem',data: traverse(node.data),};},},firstItem: {downgrade(node, traverse): NodeBefore {return {$type: 'takeFirst',data: traverse(node.data),};},upgrade(node, traverse): NodeAfter {return {$type: 'head',data: traverse(node.data),};},},head: {downgrade(node, traverse): NodeBefore {return {$type: 'firstItem',data: traverse(node.data),};},},takeLast: {upgrade(node, traverse): NodeAfter {return {$type: 'lastItem',data: traverse(node.data),};},},lastItem: {downgrade(node, traverse): NodeBefore {return {$type: 'takeLast',data: traverse(node.data),};},},takeNth: {upgrade(node, traverse): NodeAfter {return {$type: 'nthItem',data: traverse(node.data),};},},nthItem: {downgrade(node, traverse): NodeBefore {return {$type: 'takeNth',data: traverse(node.data),};},},sortOrder: {downgrade(node, traverse): NodeBefore {const { iteratee, descending } = traverse(node.data);return {$type: 'sortOrder',data: {descending,iteratee: {$type: 'fn',data: {argIds: [...iteratee.data.argIds, '$$dummyItemIndex'],body: iteratee.data.body,},},},};},upgrade(node, traverse): NodeAfter {const { iteratee, descending } = traverse(node.data);const [itemArg, itemIndexArg] = iteratee.data.argIds;return {$type: 'sortOrder',data: {descending,iteratee: {$type: 'fn',data: {argIds: [itemArg],body: replaceContextWithValue(iteratee.data.body, itemIndexArg, 0),hasNamedArgs: false,},},},};},},collection: {upgrade(node, traverse): NodeAfter {const { source, transforms } = traverse(node.data);if (transforms.length === 0) return source;return {$type: 'applyTransforms',data: {target: source,transforms,},};},},applyTransforms: {downgrade(node, traverse): NodeBefore {const { target, transforms } = traverse(node.data);return {$type: 'collection',data: {source: target,transforms,},};},},legacyQuery: {downgrade(node, traverse): NodeBefore {return {$type: 'query',data: traverse(node.data),};},},query: {upgrade(node, traverse): NodeAfter {return {$type: 'legacyQuery',data: traverse(node.data),};},},fn: {upgrade(node, traverse): NodeAfter {return {$type: 'fn',data: {argIds: traverse(node.data.argIds),body: traverse(node.data.body),hasNamedArgs: false,},};},downgrade(node, traverse): NodeBefore {return {$type: 'fn',data: {argIds: traverse(node.data.argIds),body: traverse(node.data.body),},};},},})

Const migrator

migrator: Migrator<NodeBefore, NodeAfter> = createMigrator<NodeBefore, NodeAfter>({[DEFAULT]: {downgrade(node, traverse): NodeBefore {return {$type: node.$type,...mapValues(node.data, traverse),};},upgrade(node, traverse): NodeAfter {const keys = Object.keys(node).filter((k) => k !== '$type');return {$type: node.$type,data: keys.reduce((data: any, key: string) => {data[key] = traverse(node[key]);return data;}, {}),};},},apply: {upgrade(node, traverse): NodeAfter {return {$type: 'apply',data: {args: traverse(node.args),target: traverse(node.fn),},};},downgrade(node, traverse): NodeBefore {return {$type: 'apply',args: traverse(node.data.args),fn: traverse(node.data.target),};},},array: {upgrade(node, traverse): NodeAfter {return {$type: 'array',data: {items: traverse(node.nodes),},};},downgrade(node, traverse): NodeBefore {return {$type: 'array',nodes: traverse(node.data.items),};},},branch: {upgrade(node, traverse): NodeAfter {return {$type: 'tree',data: {branches: (node.branches || []).map((branch: any) => ({match: branch.match,node: traverse(branch.node),param: branch.name,})),},};},},context: {upgrade(node, traverse): NodeAfter {return {$type: 'context',data: {name: node.identifier,},};},downgrade(node, traverse): NodeBefore {return {$type: 'context',identifier: node.data.name,};},},decrement: {downgrade(node, traverse): NodeBefore {return {$type: 'subtract',operands: [traverse(node.data.operand), { $type: 'value', value: 1 }],};},},get: {upgrade(node, traverse): NodeAfter {// TODO: Handle the item placeholder (first, last, nth, ...)const key =node.childGetter.$type === 'key'? traverse(node.childGetter.key): traverse(node.childGetter); // TODO: Is this right?return {$type: 'get',data: {subject: traverse(node.subject),key,},};},downgrade(node, traverse): NodeBefore {// TODO: Handle the item placeholder (first, last, nth, ...)return {$type: 'get',childGetter: {$type: 'key',key: traverse(node.data.key),},subject: traverse(node.data.subject),};},},increment: {downgrade(node, traverse): NodeBefore {return {$type: 'add',operands: [traverse(node.data.operand), { $type: 'value', value: 1 }],};},},match: {upgrade(node, traverse): NodeAfter {return {$type: 'match-pattern',data: {regex: traverse(node.regex),subject: traverse(node.subject),},};},},'match-pattern': {downgrade(node, traverse): NodeBefore {return {$type: 'match',regex: traverse(node.data.regex),subject: traverse(node.data.subject),};},},multiple: {upgrade(node, traverse): NodeAfter {return {$type: 'parallel',data: {operations: (node.nodes || []).map(traverse),},};},},parallel: {downgrade(node, traverse): NodeBefore {return {$type: 'parallel',nodes: traverse(node.data.operations),};},upgrade(node, traverse): NodeAfter {return {$type: 'parallel',data: {operations: traverse(node.nodes),},};},},param: {upgrade(node, traverse): NodeAfter {return {$type: 'param',data: {name: node.id,},};},downgrade(node, traverse): NodeBefore {return {$type: 'param',id: node.data.name,};},},query: {upgrade(node, traverse): NodeAfter {return {$type: 'query',data: {root: traverse(node.root),keys: traverse(node.getters),},};},downgrade(node, traverse): NodeBefore {return {$type: 'query',root: traverse(node.data.root),getters: traverse(node.data.keys),};},},ref: {upgrade(node, traverse): NodeAfter {// TODO: Handle the item placeholder (first, last, nth, ...)const toNestedGet = (target: any, path: Array<any>): any => {const [key, ...remaining] = path;const get = {$type: 'get',data: {subject: target,key: traverse(key),},};if (remaining.length === 0) return get;return toNestedGet(get, remaining);};return toNestedGet(traverse(node.root), node.path);},},series: {upgrade(node, traverse): NodeAfter {return {$type: 'series',data: {operations: traverse(node.nodes),},};},downgrade(node, traverse): NodeBefore {return {$type: 'series',nodes: traverse(node.data.operations),};},},'sort-order': {upgrade(node, traverse): NodeAfter {return {$type: 'sortOrder',data: {descending: node.descending,iteratee: traverse(node.iteratee),},};},},sortOrder: {downgrade(node, traverse): NodeBefore {return {$type: 'sort-order',descending: node.data.descending,iteratee: traverse(node.data.iteratee),};},},'take-first': {upgrade(node, traverse): NodeAfter {return { $type: 'takeFirst', data: {} };},},takeFirst: {downgrade(node, traverse): NodeBefore {return { $type: 'take-first' };},},'take-last': {upgrade(node, traverse): NodeAfter {return { $type: 'takeLast', data: {} };},},takeLast: {downgrade(node, traverse): NodeBefore {return { $type: 'take-last' };},},'take-nth': {upgrade(node, traverse): NodeAfter {return {$type: 'takeNth',data: {index: traverse(node.index),},};},},takeNth: {downgrade(node, traverse): NodeBefore {return {$type: 'take-nth',index: traverse(node.data.index),};},},tree: {downgrade(node, traverse): NodeBefore {const branches = node.data.branches || [];const isSimpleTree = branches.every((branch: any) => !(branch.match || '').startsWith('$$match:'),);if (isSimpleTree) {return {$type: 'tree',branches: branches.reduce((tree: any, branch: any) => {if (branch.match) {tree[branch.match] = traverse(branch.node);}return tree;}, {}),};}return {$type: 'tree',branches: (node.data.branches || []).map((branch: any) => ({match: branch.match,name: branch.param,node: traverse(branch.node),})),};},upgrade(node, traverse): NodeAfter {return {$type: 'tree',data: {branches: toPairs(node.branches).map(([name, node]) => ({match: name,node: traverse(node),})),},};},},'with-context': {upgrade(node, traverse): NodeAfter {return {$type: 'withContext',data: {target: traverse(node.node),values: mapValues(node.context),},};},},withContext: {downgrade(node, traverse): NodeBefore {return {$type: 'with-context',node: traverse(node.data.target),context: mapValues(traverse),};},},})

Const musterTypesMap

musterTypesMap: MusterTypeMap

Const musterVersion

musterVersion: any = require('@dws/muster-version')

Let nextPopId

nextPopId: number = 1

Let nextShiftId

nextShiftId: number = 1

Const nil

nil: Matcher<null, never> = createMatcher<null, never>('nil', (value: any) => value === null)

Const nodeDefinition

nodeDefinition: Matcher<NodeDefinition> = createMatcher('nodeDefinition',isNodeDefinition,)

Const nodeDefinition

nodeDefinition: HashFunction<NodeDefinition> = hash.registerTypeHasher(graphTypes.nodeDefinition,(value: NodeDefinition): string => value.id,)

Const nodeDependency

nodeDependency: Matcher<NodeDependency> = types.shape({allowErrors: types.optional(types.bool),allowPending: types.optional(types.bool),acceptNil: types.optional(types.bool),until: types.optional(types.shape({predicate: types.func,errorMessage: types.optional(types.func),}),),once: types.optional(types.bool),invalidate: types.optional(types.bool),target: types.oneOfType([nodeDefinition, graphNode]),})

Const nodeDependency

nodeDependency: HashFunction<NodeDependency> = hash.registerTypeHasher(graphTypes.nodeDependency,nodeDependencyShapeHasher,)

Const nodeDependencyShapeHasher

nodeDependencyShapeHasher: HashFunction<NodeDependency> = hash.type(graphTypes.nodeDependency)

Const nodeType

nodeType: HashFunction<NodeType> = hash.registerTypeHasher(graphTypes.nodeType,(value: NodeType) => value.name,)

Const nodeType

nodeType: Matcher<NodeType> = createMatcher('nodeType', isNodeType)

Const nodeTypes

nodeTypes: Dictionary<object> = mapValues(getMusterNodeTypesMap(), (nodeType) => ({operations: Object.keys((nodeType as DynamicNodeType).operations || {}),}))

Const nodeTypesMap

nodeTypesMap: NodeTypeMap

Const number

number: Matcher<number, never> = createMatcher<number, never>('number',(value: any) => typeof value === 'number',)

Const object

object: HashFunction<object> = unique as HashFunction<object>

Const object

object: Matcher<object, never> = createMatcher<object, never>('object', (value: any) => isPlainObject(value))

Const objectOf

objectOf: ValueHasherFactory<object, Matcher<Object, any>> = (<T>() =>createHasherFactory('objectOf',(matcher: Matcher<T, any>,): HashFunction<{[key: string]: T;}> => {const valueHasher = type(matcher);return (value: { [key: string]: T }): string => {let hash = 'm(';const symbolKeys = Object.getOwnPropertySymbols(value);// tslint:disable-next-line:no-increment-decrementfor (let i = 0; i < symbolKeys.length; i++) {const key = symbolKeys[i];// TODO: Remove the `as any` cast once https://github.com/Microsoft/TypeScript/issues/1863 is resolvedhash += `${symbol(key)}=${valueHasher(value[key as any])}`;}const objectKeys = Object.keys(value).filter((key) => value.hasOwnProperty(key));// tslint:disable-next-line:no-increment-decrementfor (let i = 0; i < objectKeys.length; i++) {const key = objectKeys[i];hash += `${string(key)}=${valueHasher(value[key])}|`;}return `${hash})`;};},))()

Const objectToTreeDeprecationWarning

objectToTreeDeprecationWarning: function = deprecated({old: 'objectToTree',new: 'toNode',})

Type declaration

    • (): void
    • Returns void

Const oneOf

oneOf: ValueHasherFactory<Object, Object[]> = (<T>() =>createHasherFactory('oneOf',(values: Array<T>): HashFunction<T> => {return (value: T): string => `p${values.indexOf(value)}`;},))()

Const oneOfType

oneOfType: ValueHasherFactory<Object, Matcher<Object, any>[]> = (<T>() =>createHasherFactory('oneOfType',(matchers: Array<Matcher<T, any>>): HashFunction<T> => {const matcherHasherPairs = matchers.map((matcher) => [matcher, type(matcher)] as [Matcher<T>, HashFunction<T>],);return (value: T): string => {// tslint:disable-next-line:no-increment-decrementfor (let index = 0; index < matcherHasherPairs.length; index++) {const [matcher, hasher] = matcherHasherPairs[index];if (matcher(value)) {return `${index}:${hasher(value)}`;}}return 'u';};},))()

Const operation

operation: operation & object = Object.assign(// tslint:disable-next-line:ter-prefer-arrow-callbackfunction operation(definition: MusterOperation): MusterOperation {return definition;},{only: (definition: MusterOperation): MusterOperation => {return {only: true,...operation(definition),};},skip: (definition: MusterOperation): MusterOperation => {return {skip: true,...operation(definition),};},},)

Const operationType

operationType: Matcher<OperationType> = createMatcher('operationType',isOperationType,)

Const operationType

operationType: HashFunction<OperationType> = hash.registerTypeHasher(graphTypes.operationType,(value: OperationType) => value.name,)

Const operationTypesMap

operationTypesMap: OperationTypeMap

Const optional

optional: ValueHasherFactory<undefined | Object, Matcher<Object, any>> = (<T>() =>createHasherFactory('optional',(matcher: Matcher<T, any>): HashFunction<T | undefined> => {const typeHasher = type(matcher);return (value: T | undefined): string => {if (typeof value === 'undefined' || value === null) return 'u';return typeHasher(value);};},))()

Const proxiedNode

proxiedNode: Matcher<ProxiedNode> = createMatcher('proxiedNode', isProxiedNode)

Const proxiedNode

proxiedNode: HashFunction<ProxiedNode> = hash.registerTypeHasher(graphTypes.proxiedNode,(value: ProxiedNode): string => `P(${getProxiedNodeValue(value).id})`,)

push

push: push

Const registerJestMatchers

registerJestMatchers: (Anonymous function) = once(() => {const jestExpect = global.expect;global.expect = Object.assign((received: any) => {const matchers = jestExpect(received);matchers.toEqual = decorateMatcher(matchers.toEqual);matchers.toHaveBeenCalledWith = decorateMatcher(matchers.toHaveBeenCalledWith);matchers.toHaveBeenLastCalledWith = decorateMatcher(matchers.toHaveBeenLastCalledWith);return matchers;}, jestExpect);setUnitTestMatcher(isJestAsymetricMatcher);})

Const saveHash

saveHash: ValueHasherFactory<Object, Matcher<Object, any>> = (<T>() =>createHasherFactory('saveHash',(matcher: Matcher<T, any>): HashFunction<T> => {const typeHasher = type(matcher);return (value: T): string => {if ((value as any)['$$hash']) return (value as any)['$$hash'];const hash = typeHasher(value);if ((typeof value === 'object' && value !== null) || typeof value === 'function') {Object.defineProperty(value, '$$hash', {value: hash,enumerable: false,configurable: true,});}return hash;};},))()

Const scope

scope: HashFunction<Scope> = hash.registerTypeHasher(graphTypes.scope,(value: Scope) => value.id,)

Const scope

scope: Matcher<Scope> = createMatcher('scope', isScope)

Const shape

shape: ValueHasherFactory<Object, object> = (<T extends { [key in keyof T]: T[key] }>() =>createHasherFactory('shape',(fields: ShapeFields<T>): HashFunction<T> => {const propHashers = Object.keys(fields).map((key) => ({key,hash: type((fields as any)[key]),}));return (value: T): string => {let hash = 's(';// tslint:disable-next-line:no-increment-decrementfor (let i = 0; i < propHashers.length; i++) {const propHasher = propHashers[i];hash += `${propHasher.hash((value as any)[propHasher.key])}|`;}return `${hash})`;};},))()

Const showCollectionDeprecationWarning

showCollectionDeprecationWarning: function = deprecated({old: 'collection',new: 'applyTransforms',})

Type declaration

    • (): void
    • Returns void

Const showGetItemsDeprecationWarning

showGetItemsDeprecationWarning: function = deprecated({old: 'getItems',new: 'applyTransforms',})

Type declaration

    • (): void
    • Returns void

Const showRefArrayDeprecationWarning

showRefArrayDeprecationWarning: function = deprecated({ old: 'ref([...])', new: 'ref(...)' })

Type declaration

    • (): void
    • Returns void

Const showRelativeArrayDeprecationWarning

showRelativeArrayDeprecationWarning: function = deprecated({old: 'relative([...])',new: 'relative(...)',})

Type declaration

    • (): void
    • Returns void

Const showStrlenDeprecationWarning

showStrlenDeprecationWarning: function = deprecated({old: 'strlen',new: 'length',})

Type declaration

    • (): void
    • Returns void

Const stream

stream: "/Users/wragdav/db-projects/muster/packages/muster/src/utils/stream" = _stream

Const string

string: Matcher<string, never> = createMatcher<string, never>('string',(value: any) => typeof value === 'string',)

Const stringHash

stringHash: any = require('string-hash')

Const symbol

symbol: HashFunction<symbol> = ((): HashFunction<symbol> => {const symbolToIdMap = new Map<symbol, string>();return (value: symbol) => {const symbolId = symbolToIdMap.get(value);if (symbolId) return symbolId;const newSymbolId = `$${symbolToIdMap.size}`;symbolToIdMap.set(value, newSymbolId);return newSymbolId;};})()

Const symbol

symbol: Matcher<symbol, never> = createMatcher<symbol, never>('symbol',(value: any) => typeof value === 'symbol',)

Let transformMiddlewares

transformMiddlewares: MiddlewareTransformer = identity

Const treeToObjectDeprecationWarning

treeToObjectDeprecationWarning: function = deprecated({old: 'treeToObject',new: 'valueOf',})

Type declaration

    • (): void
    • Returns void

Const types

types: "/Users/wragdav/db-projects/muster/packages/muster/src/utils/types" = _types

Let uid

uid: number = 0

Const unique

unique: HashFunction<Object> = (<T>(): HashFunction<T> => {let uid = 0;// tslint:disable-next-line:no-increment-decrementreturn (value: T): string => `*${++uid}`;})()

unshift

unshift: unshift

Const untilBooleanValueNodeItem

untilBooleanValueNodeItem: NodeDependencyUntilCondition = untilBooleanValueNode(ArrayNodeType, 'item')

Const untilBooleanValuePredicate

untilBooleanValuePredicate: NodeDependencyUntilCondition = untilBooleanValueNode(ArrayListNodeType, 'predicate')

Const untilIntegerValueIndex

untilIntegerValueIndex: NodeDependencyUntilCondition = untilIntegerValueNode(AddItemAtNodeType, 'index')

Const untilIsPositiveIntegerValueNode

untilIsPositiveIntegerValueNode: NodeDependencyUntilCondition = untilPositiveIntegerValueNode(NthItemNodeType, 'index')

Const untilIsValueNode

untilIsValueNode: NodeDependencyUntilCondition = untilValueNode(GroupByNodeType, 'predicate')

Const untilIsValueNode

untilIsValueNode: NodeDependencyUntilCondition = untilValueNode(SortNodeType, 'predicate')

Const untilIsValueNode

untilIsValueNode: NodeDependencyUntilCondition = untilValueNode(FilterNodeType, 'predicate')

Const untilPositiveIntegerLength

untilPositiveIntegerLength: NodeDependencyUntilCondition = untilPositiveIntegerValueNode(SliceNodeType, 'length')

Const untilPositiveIntegerOffset

untilPositiveIntegerOffset: NodeDependencyUntilCondition = untilPositiveIntegerValueNode(SliceNodeType, 'offset')

Const untilPositiveIntegerOffset

untilPositiveIntegerOffset: NodeDependencyUntilCondition = untilPositiveIntegerValueNode(SkipNodeType, 'offset')

Const untilPositiveNumItemsNode

untilPositiveNumItemsNode: NodeDependencyUntilCondition = untilPositiveIntegerValueNode(TakeNodeType, 'numItems')

Const untilPositiveValueIndex

untilPositiveValueIndex: NodeDependencyUntilCondition = untilIntegerValueNode(RemoveItemAtNodeType, 'index')

Const untilValidSeparator

untilValidSeparator: NodeDependencyUntilCondition = untilStringValueNode(JoinNodeType, 'separator')

Const version

version: any = require('@dws/muster-version')

Const xhr

xhr: any = require('xhr')

Functions

action

  • Creates a new instance of an action node, which is a type of NodeDefinition that allows for defining reusable fragments of code which can interact with the graph. The action on its own is treated as a data-node - just like a value or an array. It can be used as a target for a call or apply nodes. See the call and apply documentation to learn more about invoking actions.

    The action can return three types of values:

    • void/undefined: for very simple actions that don't interact with the graph
    • A NodeDefinition: an output of the action. This node can be resolved later.
    • An iterator of GraphNodes: the most common use for the action. The action body can be defined as a generator function. This way the action can perform complex operations. See the "Using generators in an action node" example to learn more.

    The action node can be thought of as a computed node with few differences. The computed must statically declare its dependencies. actions, however, declare only a number of arguments, without linking them to NodeDefinitions. These arguments will be passed to the action at the time of calling or applying. Another difference is that the computed must always resolve to a single NodeDefinition, whereas the action has no such limitations.

    example

    Simple actions

    import muster, { action, call } from '@dws/muster';
    
    const app = muster({
      logWhenCalled: action(() => {
        console.log('Action has been called');
      }),
    });
    
    console.log('Calling action');
    const output = await app.resolve(call('logWhenCalled'));
    // output === undefined
    
    // Console output:
    // Calling action
    // Action has been called

    This example demonstrates how to define a simple action that does something when called with the help of a call node. See the call documentation to learn more about calling actions. Note that the function returns value(undefined).

    example

    Actions with arguments

    import muster, { action, call } from '@dws/muster';
    
    const app = muster({
      logFullName: action((firstName, lastName) => {
        console.log(`Hello, ${firstName} ${lastName}!`);
      }),
    });
    
    console.log('Calling action');
    const output = await app.resolve(call('logFullName', ['Bob', 'Builder']));
    // output === undefined
    
    // Console output:
    // Calling action
    // Hello, Bob Builder!

    The action node can also define a number of arguments. These arguments will be supplied from the calling call or apply nodes. As in the previous example, the function returns undefined.

    Much like the computed node, the parameters of the action are first resolved to their most basic form (here with the help of a resolve node). Resolved values that are a value, a tree or an array are run through the valueOf helper. This simplifies the implementation of your actions by not forcing you to deal with NodeDefinitions inside the action's function body.

    example

    Returning a value from an action

    import muster, { action, call } from '@dws/muster';
    
    const app = muster({
      getFullName: action((firstName, lastName) => `${firstName} ${lastName}`),
    });
    
    console.log('Calling action');
    const fullName = await app.resolve(call('getFullName', ['Rosalind', 'Franklin']));
    // fullName === 'Rosalind Franklin'
    
    console.log(fullName);
    
    // Console output:
    // Calling action
    // Rosalind Franklin

    This example shows how to return values from an action. As with the computed, the value returned from the action function is converted to a value if is not already a NodeDefinition.

    example

    Returning a computed node from an action

    import muster, { action, call, computed, value } from '@dws/muster';
    
    const app = muster({
      getGreeting: action((firstName, lastName) =>
        computed([value(`${firstName} ${lastName}`)], (fullName) => `Hello, ${fullName}`),
      ),
    });
    
    console.log('Getting a greeting');
    const greeting = await app.resolve(call('getGreeting', ['Rosalind', 'Franklin']));
    // greeting === 'Hello, Rosalind Franklin'
    
    console.log(greeting);
    
    // Console output:
    // Getting a greeting
    // Hello, Rosalind Franklin

    The return node type of an action is not limited to a value. The action can return any type of a NodeDefinition. This example demonstrates the action returning a computed that resolves to a greeting.

    example

    Using generators in action nodes

    import muster, { action, call, ref } from '@dws/muster';
    
    const app = muster({
      greeting: 'Hello',
      getGreeting: action(function*(name) {
        const greeting = yield ref('greeting');
        return `${greeting}, ${name}`;
      }),
    });
    
    console.log('Getting a greeting');
    const greeting = await app.resolve(call('getGreeting', ['Rosalind']));
    // greeting === 'Hello, Rosalind'
    
    console.log(greeting);
    
    // Console output:
    // Getting a greeting
    // Hello, Rosalind

    This example shows the use of generator functions as the body of an action. Generators offer greater flexibility than a simple computed. They allow writing code which seem to be executed in series, but may in fact be making asynchronous requests to external APIs or remote instances of Muster.

    Note the use of a yield keyword inside of the generator function. Yielding a NodeDefinition instructs Muster to resolve a given node to its most basic form (just like with the parameters). In this example, the ref resolves to a value, which gets un-wrapped into a more basic representation (with the help of a valueOf helper) and assigned to the greeting variable. Muster actions also allow for returning an array of NodeDefinitions (e.g. ref). See the "Yielding multiple graph nodes" example to learn more.

    example

    Yielding multiple graph nodes

    import muster, { action, call, ref } from '@dws/muster';
    
    const app = muster({
      firstName: 'Rosalind',
      lastName: 'Franklin',
      getFullName: action(function*() {
        const [firstName, lastName] = yield [
          ref('firstName'),
          ref('lastName'),
        ];
        return `${firstName} ${lastName}`;
      }),
    });
    
    console.log('Getting a full name');
    const fullName = await app.resolve(call('getFullName'));
    // fullName = 'Rosalind Franklin';
    
    console.log(fullName);

    This example shows how to yield multiple NodeDefinitions. Muster tries to resolve both of these values simultaneously before returning the result. The result of such operation is an array of un-wrapped NodeDefinitions.

    One major benefit of this kind of batching is most visible when making requests to a remote Muster instance. Normally the yield keyword waits for the non-pending result to be returned. In a situation where the application needs to load two separate branches that come from a server, it's best to batch them into a single request. By yielding an array we're letting Muster know that these branches can be resolved simultaneously. See the proxy and remote documentation for more information.

    example

    Yielding named nodes

    import muster, { action, call, ref } from '@dws/muster';
    
    const app = muster({
      firstName: 'Rosalind',
      lastName: 'Franklin',
      getFullName: action(function*() {
        const { first, last } = yield {
          first: ref('firstName'),
          last: ref('lastName'),
        };
        return `${first} ${last}`;
      }),
    });
    
    console.log('Getting a full name');
    const fullName = await app.resolve(call('getFullName'));
    // fullName = 'Rosalind Franklin';
    
    console.log(fullName);

    This example shows how to yield multiple NodeDefinitions as named nodes. The benefit of using this form of yielding when compared to the previous example is that it's less prone to errors. When yielding an array it is possible to accidentally do const [last, first] = yield [ref('firstName'), ref('lastName')]; This code would work perfectly fine, but the values would end up in incorrectly named variables. The ability to yield named nodes mitigates this category of errors.

    example

    Create an action with named args

    import muster, { action, call } from '@dws/muster';
    
    const app = muster({
      greet: action(({ name }) => `Hello, ${name}!`),
    });
    
    await app.resolve(call('greet', { name: 'Bob' }));
    // === 'Hello, Bob!'

    This example shows how to create and call an action node with named arguments.

    Parameters

    Returns ActionNodeDefinition

add

  • Creates a new instance of an add which is a type of NodeDefinition used to compute the sum of multiple number-based values. The add takes any number of operands. It will throw an error if the number of operands is below 2 as it doesn't make sense to do the sum operation with a single operand.

    example

    Add two numbers

    import muster, { add, ref } from '@dws/muster';
    
    const app = muster({
      five: 5,
      three: 3,
    });
    
    const result = await app.resolve(
      add(ref('five'), ref('three')),
    );
    // result === 8

    This example shows how to compute a sum of 5 and 3 with the use of an add.

    example

    Add five numbers

    import muster, { add, computed, ref, variable } from '@dws/muster';
    
    const app = muster({
      five: 5,
      four: computed([], () => 4),
      three: variable(3),
      two: add(ref('one'), ref('one')),
      one: 1,
    });
    
    const result = await app.resolve(
      add(ref('five'), ref('four'), ref('three'), ref('two'), ref('one')),
      // Same as 5+4+3+2+1 in JS
    );
    // result === 15

    This example shows how to add five differently computed numbers. As mentioned in the description above, this node can handle any number of operands as long as they resolve to a numeric value.

    Parameters

    Returns AddNodeDefinition

addActionToCache

addHashSetItem

addItemAt

  • Creates an instance of an addItemAt node, which is a type of a graph node used when inserting an item into a mutable collection at a specific index.

    example

    Insert a number to a mutable collection

    import muster, { addItemAt, arrayList, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([1, 2, 3]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(addItemAt(ref('numbers'), 5, 1));
    
    // Console output:
    // [1, 2, 3]
    // [1, 5, 2, 3]

    This example shows how to insert a new item to a mutable collection.

    example

    Insert a branch to a mutable collection

    import muster, { addItemAt, arrayList, entries, key, query, ref, toNode } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { firstName: 'Lizzie', lastName: 'Ramirez' },
        { firstName: 'Charlotte', lastName: 'Schneider' },
      ]),
    });
    
    app.resolve(query(ref('people'), entries({
      firstName: key('firstName'),
    }))).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(
      addItemAt(ref('people'), toNode({ firstName: 'Genevieve', lastName: 'Patrick' }), 1),
    );
    
    // Console output:
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }]
    // [{ firstName: 'Lizzie' }, { firstName: 'Genevieve' }, { firstName: 'Charlotte' }]

    This example shows how to insert a new branch to a mutable collection.

    Parameters

    Returns AddItemAtNodeDefinition

addItemAtOperation

addLineNumbers

  • addLineNumbers(lines: Array<string>, options?: object): Array<string>
  • Parameters

    • lines: Array<string>
    • Default value options: object = {}
      • Optional minLength?: undefined | number
      • Optional offset?: undefined | number

    Returns Array<string>

addNodeToCache

addScopeToCache

addStreamListeners

  • addStreamListeners<T>(stream: Stream<T>, options: object): Stream<T>
  • Type parameters

    • T

    Parameters

    • stream: Stream<T>
    • options: object
      • Optional invalidate?: undefined | function
      • Optional subscribe?: undefined | function
      • Optional unsubscribe?: undefined | function

    Returns Stream<T>

and

  • Creates a new instance of an and node, which introduces the and expression. It checks if every operand of this and is truthy. The conversion to boolean is done with the help of the Boolean JS function. It requires every operand to resolve to a value. It throws an error if an operand resolves to a graph node other than a value.

    example

    Different variants of and operands

    import muster, { and, computed, value } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(and(true)) // === true
    await app.resolve(and(false)) // === false
    await app.resolve(and(value(true))) // === true - it is equivalent to and(true)
    await app.resolve(and('hello world')) // === true
    await app.resolve(and(true, false)) // === false
    await app.resolve(and(computed([], () => false))) // === false
    await app.resolve(and(computed([], () => true))) // === true
    await app.resolve(and(computed([], () => true), true)) // === true
    await app.resolve(and(computed([], () => true), false)) // === false
    example

    Dynamic operands

    import muster, { and, gt, lte, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      balance: variable(100),
      stake: variable(51),
      canPlaceBet: and(
        gt(ref('stake'), 0),
        lte(ref('stake'), ref('balance')),
      ),
    });
    
    app.resolve(ref('canPlaceBet')).subscribe((res) => {
      console.log(`Can place bet: ${res}`);
    });
    
    console.log('Changing stake to 150');
    await app.resolve(set('stake', 150));
    
    console.log('Changing balance to 150');
    await app.resolve(set('balance', 150));
    
    // Console output:
    // Can place bet: true
    // Changing stake to 150
    // Can place bet: false
    // Changing balance to 150
    // Can place bet: true

    This example shows how the and can be used in conjunction with other logic graph nodes to produce expected results. The canPlaceBet node checks if the stake is greater than zero and if the stake can be covered by user's balance. This is done thanks to gt and lte.

    Parameters

    Returns AndNodeDefinition

Const any

  • any(value: any): string

apply

  • Creates an instance of an apply node, which is a node used to apply arguments to a NodeDefinition that implements a call method, e.g. action or fn. Unlike the call, which invokes the target function only once, the apply maintains an active subscription to the input arguments and to the output value of the function. This means that whenever the input arguments change, the target function body will be re-invoked, and whenever the result of the target function changes, a new value will be returned. You can think of an apply as analogous to an observable stream that combines the given input argument streams and transforms them into an output stream. Multiple subscriptions to the apply do not cause multiple executions of the callable node body.

    example

    Apply arguments to an fn node

    import muster, { apply, fn, format, ref } from '@dws/muster';
    
    const app = muster({
      getFullName: fn((firstName, lastName, title) => format('${title} ${firstName} ${lastName}', {
        firstName,
        lastName,
        title
      })),
    });
    
    console.log('Applying the graph function');
    const result = await app.resolve(
      apply(['Rosalind', 'Franklin', 'Ms'], ref('getFullName')),
    );
    // result === 'Ms Rosalind Franklin'
    
    console.log(result);
    
    // Console output:
    // Applying the graph function
    // Ms Rosalind Franklin

    This example shows how to supply arguments to an fn - the same can be done with an action. There are no restrictions on the type of the arguments. Note the use of a format to combine strings. See the format documentation for more information.

    example

    Stream-like nature of apply

    import muster, { apply, fn, format, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      greeting: variable('Hello'),
      getGreeting: fn((greeting, name) => format('${greeting}, ${name}', { greeting, name })),
    });
    
    console.log('Applying getGreeting');
    app.resolve(apply([ref('greeting'), 'Bob'], ref('getGreeting'))).subscribe((output) => {
      console.log(output);
    });
    
    console.log('Changing the greeting');
    await app.resolve(set('greeting', 'Goodbye'));
    
    // Console output:
    // Applying getGreeting
    // Hello, Bob
    // Changing the greeting
    // Goodbye, Bob

    This example shows how the apply node can be used to create a stream that computes a new value every time its input arguments change their value.

    Parameters

    Returns ApplyNodeDefinition

  • Parameters

    Returns ApplyNodeDefinition

  • Parameters

    Returns ApplyNodeDefinition

applyReducerStep

applyTransforms

  • Creates a new instance of a applyTransforms node, which is a type of NodeDefinition which can apply transforms to a collection of items. These items can be either values or trees. It's recommended that items in a collection be of the same type (and in case of tree - shape).

    Collections support a number of transforms. These transforms can be applied in any order to a target collection.

    • count (count) - Gets the count of items found in the collection
    • filter (filter) - Filters the applyTransforms based on a given predicate
    • map (map) - Performs a map transform on the every item of the collection
    • slice (slice) - Slices the collection based on a defined range
    • sort (sort) - Sorts the items based on a given predicate
    • groupBy (groupBy) - Groups the items based on a given predicate
    • firstItem (firstItem) - Takes a first item of the collection
    • lastItem (lastItem) - Takes the last item of the collection
    • nthItem (nthItem) - Takes nth (0-based) item of the collection
    • take (take) - Takes a given number of items from the collection

    At creation, every applyTransforms requires a source for its items. Currently Muster supports following collection data sources:

    • array (array) - An in-memory array.
    • arrayList (arrayList) - An in-memory mutable array
    • nodeList (nodeList)) - An in-memory array of GraphNodes.
    • another applyTransforms node - This can be useful when one collection contains partially filtered items and another collection uses the output of it and applies another set of transforms to it
    • a remote collection - See the proxy and remote documentation to learn more.
    example

    Filtering collection

    import muster, { applyTransforms, filter, gt, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: applyTransforms(
        [1, 2, 3, 4, 5],
        [
          // Filter items with a value greater than 3
          filter((item) => gt(item, 3))
        ],
      ),
    });
    
    const numbers = await app.resolve(query(ref('numbers'), entries()));
    // numbers === [4, 5]

    This example shows the basic use of the filter transform. Here the transform is applied directly to the numbers applyTransforms, but it is also possible to apply the transform in the query. See the "Building the query with transforms" example to learn more.

    example

    Linking collection

    import muster, { applyTransforms, filter, gt, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      originalNumbers: [1, 2, 3],
      filteredNumbers: applyTransforms(
        ref('originalNumbers'),
        [filter((item) => gt(item, 1))],
      ),
      allNumbers: ref('originalNumbers'),
    });
    const filteredNumbers = await app.resolve(
      query(ref('filteredNumbers'), entries()),
    );
    // filteredNumbers === [2, 3]
    
    const allNumbers = await app.resolve(
      query(ref('allNumbers'), entries()),
    );
    // allNumbers === [1, 2, 3]

    This example shows how to use a ref as the target for the applyTransforms.

    Parameters

    Returns ApplyTransformsNodeDefinition

applyTransforms

array

arrayList

  • Creates a new instance of an arrayList node, which is a type of a NodeDefinition used when creating a mutable in-memory array. This array allows for a following operations:

    When modified in any way this array retains the state for as long as the parent scope exists, or until a reset operation is executed on the array. This behaviour resembles the behaviour of a variable node.

    example

    Create a simple array

    import muster, { arrayList, entries, push, pop, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([1, 3, 2]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((numbers) => {
      console.log(numbers);
    });
    
    await app.resolve(push(ref('numbers'), 4));
    await app.resolve(pop(ref('numbers'))); // === 4
    await app.resolve(pop(ref('numbers'))); // === 2
    await app.resolve(pop(ref('numbers'))); // === 3
    await app.resolve(pop(ref('numbers'))); // === 1
    await app.resolve(pop(ref('numbers'))); // === null
    await app.resolve(pop(ref('numbers'))); // === null
    
    // Console output:
    // [1, 3, 2]
    // [1, 3, 2, 4]
    // [1, 3, 2]
    // [1, 3]
    // [1]
    // []

    This example shows how to create a simple mutable array and use a few operations on it.

    Parameters

    Returns ArrayListNodeDefinition

arrayOf

arrayReducer

ascending

assertEnoughOperands

  • assertEnoughOperands(operands: Array<any>): void

assertEnoughOperands

  • assertEnoughOperands(operands: Array<any>): void

assertEnoughOperands

  • assertEnoughOperands(operands: Array<any>): void

assignCachedActionResult

assignPathIfError

  • assignPathIfError<T>(node: T): T

assignPlaceholderPath

assignRemotePathIfError

  • assignRemotePathIfError<T>(node: T): T

attachMetadata

batchRequestsMiddleware

behaviorSubject

  • behaviorSubject<T>(initialValue: T): Subject<T>

bool

  • bool(value: boolean): string

buildFormatInput

buildNodeTypesMap

buildOperationTypesMap

buildQuerySetChildForCallerOrSetterNode

buildQuerySetChildForCatchError

buildQuerySetChildForDefer

buildQuerySetChildForIsPending

buildQuerySetChildForKey

buildQuerySetChildForQueryKey

buildQuerySetChildrenForEntriesNode

buildQuerySetChildrenForFieldsNode

buildQuerySetChildrenForQueryChild

buildQuerySetForQuery

buildQuerySetFromQueryBuilderSnapshot

buildQuerySetOperationsForQueriesSnapshot

cacheFirstResult

  • cacheFirstResult<T>(fn: T): T

call

callOperation

canBeResolved

canResolveDependencies

  • canResolveDependencies(node: GraphNode): boolean

catchError

  • Creates a new instance of a catchError node, which is a type of a NodeDefinition used inside a query to indicate that a given part of the query can resolve to an error, and in that case it should be replaced with a given fallback value.

    example

    Fallback value when branch errors

    import muster, { catchError, error, key, query, root, value } from '@dws/muster';
    
    const app = muster({
      user: error('Some reason why user can`t be loaded'),
    });
    
    await app.resolve(query(root(), {
      user: catchError(value('Could not load user'), {
        firstName: key('firstName'),
        lastName: key('lastName'),
      }),
    })); // === 'Could not load user'

    Parameters

    Returns CatchErrorNodeDefinition

catchErrors

ceil

  • Creates a new instance of a ceil node, which is a type of a NodeDefinition used when converting a number (int or float) to a smallest integer greater or equal to the current number. It works in the same way as the Math.ceil from JavaScript.

    example

    Ceil the value

    import muster, { ceil, ref } from '@dws/muster';
    
    const app = muster({
      fivePointThree: 5.3,
    });
    
    await app.resolve(ceil(5));
    // === 5
    
    await app.resolve(ceil(5.2));
    // === 6
    
    await app.resolve(ceil(ref('fivePointThree')));
    // === 6

    Parameters

    Returns CeilNodeDefinition

charAt

  • Creates a new instance of a charAt node, which is used when extracting a specific character from string. The node expects the subject to be a value that contains a string value. It work in a similar way as the string.charAt(...) function from JS.

    example

    Extract char at

    import muster, { charAt } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(charAt(1, 'Hello world'));
    // === 'e'
    
    await app.resolve(charAt(20, 'Hello world'));
    // === null

    Parameters

    Returns CharAtNodeDefinition

choose

  • Creates a new instance of a choose node, which is used to conditionally return a different value. It works in a similar way to the ifElse node, but allows for a more concise definition when defining more than one condition.

    The conditions are defined with the help of [[case]] and otherwise nodes. Each switchOn can define any number of [[case]] cases, and MUST define exactly one otherwise node.

    example

    Simple choose node

    import muster, {
      eq,
      choose,
      gt,
      otherwise,
      ref,
      variable,
      when,
    } from '@dws/muster';
    
    const app = muster({
      input: variable(10),
      something: choose([
        when(eq(ref('input'), 10), 'It\'s ten!'),
        when(gt(ref('input'), 32), 'More than 32'),
        otherwise('Well, it\'s not ten and not more than 32'),
      ]),
    });
    
    await app.resolve(ref('something')); // === It's ten!

    Parameters

    Returns ChooseNodeDefinition

clamp

  • Creates a new instance of a clamp node, which is a type of a NodeDefinition used when retrieving a value that is clamped between minimum and maximum range.

    example

    Clamp the value

    import muster, { clamp, ref } from '@dws/muster';
    
    const app = muster({
      ten: 10,
      hundred: 100,
    });
    
    await app.resolve(clamp(31, { min: ref('ten'), max: ref('hundred') }));
    // === 31
    
    await app.resolve(clamp(9, { min: ref('ten'), max: ref('hundred') }));
    // === 10
    
    await app.resolve(clamp(101, { min: ref('ten'), max: ref('hundred') }));
    // === 100

    Parameters

    Returns ClampNodeDefinition

clear

  • Creates a clear node, which is a type of a NodeDefinition used when clearing an arrayList node.

    example

    Clear an arrayList

    import muster, { arrayList, clear, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      items: [1, 2, 3],
    });
    
    // Check the arrayList before clearing it
    await app.resolve(query(ref('items'), entries()));
    // === [1, 2, 3];
    
    await app.resolve(clear(ref('items')));
    
    // Check the arrayList after clearing it
    await app.resolve(query(ref('items'), entries()));
    // === []

    This example shows how to use the clear node to clear the arrayList.

    Parameters

    Returns ClearNodeDefinition

clearOperation

collectFieldQueries

collectItemsFieldsQueries

collectRootGetItemsQueries

collection

  • Creates a new instance of a collection node, which is a type of NodeDefinition which can handle collections of items. These items can be either values or trees. It's recommended that items in a collection be of the same type (and in case of tree - shape).

    Collections support a number of transforms. These transforms can be applied in any order to a target collection.

    • count (count) - Gets the count of items found in the collection
    • filter (filter) - Filters the collection based on a given predicate
    • map (map) - Performs a map transform on the every item of the collection
    • slice (slice) - Slices the collection based on a defined range
    • sort (sort) - Sorts the items based on a given predicate
    • groupBy (groupBy) - Groups the items based on a given predicate
    • firstItem (firstItem) - Takes a first item of the collection
    • lastItem (lastItem) - Takes the last item of the collection
    • nthItem (nthItem) - Takes nth (0-based) item of the collection
    • take (take) - Takes a given number of items from the collection

    At creation, every collection requires a source for its items. Currently Muster supports following collection data sources:

    • array (array) - An in-memory array.
    • arrayList (arrayList) - An in-memory mutable array
    • nodeList (nodeList)) - An in-memory array of GraphNodes.
    • another collection node - This can be useful when one collection contains partially filtered items and another collection uses the output of it and applies another set of transforms to it
    • a remote collection - See the proxy and remote documentation to learn more.
    deprecated
    example

    Basic collections

    import muster, { entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3], // Implicit conversion to a collection
      // Which is the same as:
      // numbers: collection([1, 2, 3]),
      // Or even more explicitly as :
      // numbers: collection(arrayDataSource([1, 2, 3]))
    });
    
    const numbers = await app.resolve(query(ref('numbers'), entries()));
    // numbers === [1, 2, 3]

    This example shows how to create a basic collection containing values, and how to access the items from it. The process of getting items out of collection requires the use of a query with an entries. See the query documentation to learn more about building queries.

    The query to the collection resolves to an array, which behaves just like a value but stores an array of NodeDefinitions.

    It is possible to get items from a collection by just resolving a ref, but such ref resolves into a nodeList which contains the item nodes as well as their scopes. This representation form is used internally when making references between collections but is not really useful for apps consuming these items.

    example

    Filtering collections

    import muster, { collection, filter, gt, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: collection(
        [1, 2, 3, 4, 5],
        [
          // Filter items with a value greater than 3
          filter((item) => gt(item, 3))
        ],
      ),
    });
    
    const numbers = await app.resolve(query(ref('numbers'), entries()));
    // numbers === [4, 5]

    This example shows the basic use of the filter transform. Here the transform is applied directly to the numbers collection, but it is also possible to apply the transform in the query. See the "Building the query with transforms" example to learn more.

    example

    Building the query with transforms

    import muster, { filter, gt, entries, query, ref, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const numbers = await app.resolve(query(ref('numbers'), withTransforms([
      filter((item) => gt(item, 3)),
    ], entries())));
    // numbers === [4, 5]

    This example shows how to include additional collection transforms within a query. It gives the same output as the code from the "Filtering collections" example.

    example

    Linking collections

    import muster, { collection, filter, gt, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      originalNumbers: [1, 2, 3],
      filteredNumbers: collection(
        ref('originalNumbers'),
        [filter((item) => gt(item, 1))],
      ),
      allNumbers: collection(ref('originalNumbers')),
    });
    const filteredNumbers = await app.resolve(
      query(ref('filteredNumbers'), entries()),
    );
    // filteredNumbers === [2, 3]
    
    const allNumbers = await app.resolve(
      query(ref('allNumbers'), entries()),
    );
    // allNumbers === [1, 2, 3]

    As mentioned in the introduction above, collections can use another collection as a data source. This example shows how to use one collection as the data source for two separate collections. One of them applies some transforms while the other one gets the items directly.

    example

    Complex items

    import muster, { entries, key, query, ref } from '@dws/muster';
    
    const app = muster({
      books: [
        { title: 'Casino Royale', author: 'Ian Fleming', year: 1953 },
        { title: 'Live and Let Die', author: 'Ian Fleming', year: 1954 },
        { title: 'The Big Four', author: 'Agatha Christie', year: 1927 },
      ],
    });
    
    const bookTitles = await app.resolve(
      query(ref('books'), entries({
        title: key('title'),
      })),
    );
    // bookTitles === [
    //   { title: 'Casino Royale' },
    //   { title: 'Live and Let Die' },
    //   { title: 'The Big Four' },
    // ];

    This example shows how to retrieve given fields from every item of the collection. Here, each collection item is a tree. This means that in order to get the value of an item, we have to make a query to specific fields of that branch. The query we made in this example requests the title of each book, but ignores the author and year.

    Parameters

    Returns NodeDefinition

combineLatest

  • Creates a new instance of a combineLatest node, which is a type of a NodeDefinition used to join the current values of multiple input nodes into a combined output. The result of resolving the input nodes is assembled into an array, maintaining the order of nodes provided to the combineLatest.

    When subscribing to a combineLatest node, a live subscription is created for each of the input nodes. This means that, unlike the the parallel node, the combineLatest will emit a new output value whenever one of its input nodes is updated.

    example

    Combining the current values of multiple input variables

    import muster, { combineLatest, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      firstName: variable('Bob'),
      lastName: variable('Jones'),
      age: variable(39),
    });
    
    app.resolve(combineLatest([
      ref('firstName'),
      ref('lastName'),
      ref('age'),
    ])).subscribe((value) => console.log(value));
    
    console.log('Setting age to 40');
    await app.resolve(set('age', 40)) // === 40
    
    // Console output:
    // ['Bob', 'Jones', 39]
    // Setting age to 40
    // ['Bob', 'Jones', 40]

    This example shows how to use the combineLatest to resolve three NodeDefinitions, whose values cause the overall result to re-emit.

    Parameters

    Returns CombineLatestNodeDefinition

combineLatest

  • combineLatest<T, V>(combine: function, streams: Array<Stream<T>>): Stream<V>

combinedMiddleware

combinedReducer

compareQuerySetChildWithPath

compareSortValue

compareSortValues

  • compareSortValues(values1: Array<SortValue>, values2: Array<SortValue>, descending: Array<boolean>): number

composeApplyNodes

composeMiddlewares

composeNestedGet

composeReducers

computeCurrentValue

computeCurrentValue

computed

  • Creates a new instance of a computed node, which is a type of a NodeDefinition mostly used when dynamically creating other NodeDefinitions based on dependencies and logic defined in thecombine function.

    dependencies is an array of NodeDefinitions which must be evaluated (see the resolve for more information) before running the combine function.

    combine is a synchronous function that must return a valid NodeDefinition every time it's called. This function receives a number of arguments equal to the length of dependencies array. Each argument is a resolved value of the matching dependency. If the dependency has resolved to a NodeDefinition which is value, tree or array it is run through the valueOf helper in order to extract its value for easier use in the combine function.

    computed nodes can be created using the computed helper exported from @dws/muster package: import { computed } from '@dws/muster';

    This node is not serializable.

    example

    Computed nodes without dependencies

    import { computed } from '@dws/muster';
    
    computed([], () => 'Hello world');

    This is one of the most basic usages of a computed node. This node has no dependencies (note the empty dependencies array) and a pure combine function. One more thing to note is that the output of the combine function is not a NodeDefinition but a string. This works because the computed sanitizes the output of the combine function by running it through a toValue helper. If it encounters a value which is not a node definition (see isNodeDefinition), it wraps it in a value node.

    The same could be achieved by creating the following computed node:

    import { computed, value } from '@dws/muster';
    
    computed([], () => value('Hello world'));
    example

    Computed nodes with non-dynamic dependencies

    import { computed, value } from '@dws/muster';
    
    computed([value('Bob')], (name) => `Hello ${name}`);

    In this example we have created a computed node with one dependency: value('Bob'), and a combine function that adds the value of this dependency to the 'Hello ' string.

    Note the type of the name parameter. The combine function expects it to be a string and it is, thanks to the automatic argument unwrapping process described above.

    As discussed, the unwrapping happens only for certain node types. Consider the following example:

    import { computed, tree } from '@dws/muster';
    
    const testBranch = tree({});
    
    computed([testBranch], (val) => {
      return val === testBranch; // true
    });

    This time we used a tree as a dependency of the computed. The branch has not been unwrapped as there's no more basic way of representing it in muster, so it is passed directly to the combine function.

    example

    Returning graph nodes other than value

    import muster, { computed, ref } from '@dws/muster';
    
    const app = muster({
      first: 'Bob',
      last: 'Johnson',
      fullName: computed([ref('first')], (first) =>
        computed([ref('last')], (last) => `${first} ${last}`),
      ),
    });

    Computed nodes do not have to return simple values. They can also return any kind of NodeDefinition. This example demonstrates returning a nested computed node where each node is responsible for retrieving just one dependency. As you can imagine code like this is not the most efficient and could be optimised by combining both of these computeds into one.

    import { computed, ref } from '@dws/muster';
    
    computed([ref('first'), ref('last')], (first, last) => `${first} ${last}`)

    On the other hand it demonstrates that an output of a computed can be any other NodeDefinition.

    Retrieving the value of fullName node will cause the first computed to be evaluated. As it depends on the node first, muster would retrieve the value of node first and run the combine function with the value of first node. As the output of this computed is a dynamic node Muster will evaluate that as well.

    example

    Reacting to changing dependencies

    import muster, { computed, ref, set, value, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
      greeting: computed([ref('name')], (name) => `Hello ${name}`),
    });
    
    let latestGreeting;
    app.resolve(ref('greeting')).subscribe((greeting) => {
      latestGreeting = greeting;
    });
    
    // latestGreeting === 'Hello Bob'
    
    await app.resolve(set('name', 'John'));
    
    // latestGreeting === 'Hello John'

    In this example we're defining a computed node similar to the one in the "Computed nodes with non-dynamic dependencies" example. Note that this time instead of a value we're using a variable. You can think of a value as const keyword in javascript whilst variable is comparable to let.

    Dynamic nodes in Muster can react to changes in their dependencies' values. By creating a computed with a ref to another node in the graph we're saying that the value of this computed depends on the latest value of the ref's target node. When the value of the dependency changes, this causes the value of this computed to change - the combine function is rerun with updated values for the dependencies.

    You can find out more about set and variable in their documentation.

    Parameters

    Returns NodeDefinition

  • Parameters

    Returns NodeDefinition

  • Parameters

    Returns NodeDefinition

  • Parameters

    Returns NodeDefinition

  • Parameters

    Returns NodeDefinition

  • Parameters

    Returns NodeDefinition

  • Parameters

    Returns NodeDefinition

contains

  • Creates an instance of a contains node, which can be used to determine whether a given value or item exists in a collection. Existence is determined through implicit use of the eq node unless a custom comparator function is supplied.

    example

    Simple usage

    import muster, { array, contains, ref } from '@dws/muster';
    
    const app = muster({
      numbers: array([3, 2, 1]),
    });
    
    const contains3 = await app.resolve(contains(ref('numbers'), 3)));
    // contains3 === true
    const contains5 = await app.resolve(contains(ref('numbers'), 5)));
    // contains5 === false

    This example demonstrates how to assert whether a simple value exists in an array.

    example

    Usage with custom comparator

    import muster, { arrayList, contains, ref, toNode } from '@dws/muster';
    
    const app = muster({
      products: arrayList([
        { name: 'Apple', category: 'Fruit' },
        { name: 'Bicycle', category: 'Toy' },
        { name: 'Pear', category: 'Fruit' },
        { name: 'Banana', category: 'Fruit' },
      ]),
    });
    
    const containsBananaString = await app.resolve(contains(
      ref('products'),
      'Banana',
      fn((left, right) => eq(get(left, 'name'), right)),
    )));
    // containsBananaString === true
    
    const containsBananaObject = await app.resolve(contains(
      ref('products'),
      toNode({ name: 'Banana' }),
      fn((left, right) => eq(get(left, 'name'), get(right, 'name'))),
    )));
    // containsBananaObject === true

    This example demonstrates how to use a custom comparator function (in this case, an fn node) to determine equality between items. The first query uses a simple string, the second converts the supplied target item to a node to allow consistent use of the get node between collection and target.

    Parameters

    Returns ContainsNodeDefinition

containsOperation

context

  • Creates a new instance of a context node, which is a type of NodeDefinition used to access nodes stored on the current scope. The nodes can be added to the scope by the following NodeDefinitions:

    There's a significant difference between the scope and the withContext. The withContext node enables the ability of storing nodes on the scope. The scope does the same thing and additionally every node defined within that scope is locked to it. Nodes defined inside of the scope cannot access any node outside it. Such limitation does not exist for nodes defined inside the withContext.

    example

    Extract value from scope

    import muster, { computed, context, ref, scope, value } from '@dws/muster';
    
    const app = muster({
      innerScope: scope({
        greeting: computed([context('name')], (name) =>
          `Hello, ${name}`,
        ),
      }, {
        name: value('Bob'),
      }),
    });
    
    const greeting = await app.resolve(ref('innerScope', 'greeting'));
    // greeting === 'Hello, Bob'

    This example shows how to use the context to gain access to the nodes available on the scope. See the scope documentation to learn more about scopes.

    example

    Extract value from withContext

    import muster, { computed, context, ref, value, withContext } from '@dws/muster';
    
    const app = muster({
      inner: withContext({
        name: value('Bob'),
      }, {
        greeting: computed([context('name')], (name) =>
          `Hello, ${name}`,
        ),
      }),
    });
    
    const greeting = await app.resolve(ref('inner', 'greeting'));
    // greeting === 'Hello, Bob';

    This example shows how to use the context to gain access to the nodes available on the scope. See the withContext documentation to learn more.

    Parameters

    • name: string | symbol

    Returns ContextNodeDefinition

contextHasPathKey

  • contextHasPathKey(context: Context): boolean

count

  • Creates a new instance of a count node, which is a type of count transform. It is used when counting items in a collection. Applying this transform resolves the collection into a collection with a single count which contains the original items count.

    The count transform is useful if you need to refer to the current number of items from within a chain of collection transformations. If the result does not need to be passed on to another transform, it is usually easier to use the length helper within a ref path.

    example

    Basic use of the count transform

    import muster, { applyTransforms, count, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: applyTransforms(
        [1, 2, 3, 4],
        [count()],
      ),
    });
    
    const numbersCount = await app.resolve(query(ref('numbers'), entries()));
    // numbersCounts === [4]

    This example shows the basic use case for the count node. It counts the number of items present in the collection and returns a collection with one item containing the count.

    example

    Applying count in a query

    import muster, { count, entries, query, ref, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
    });
    
    const numbersCount = await app.resolve(
      query(ref('numbers'), withTransforms([count()], entries()))
    );
    // numbersCount === [4]

    Just like any transform, the count transform can be applied from within a query.

    example

    Counting items using a ref

    import muster, { length, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
    });
    
    const numbersCount = await app.resolve(ref('numbers', length()));
    // numbersCount === 4

    The count node comes with a handy utility (length) you can use as a part of a ref path. See the ref documentation to learn more about length and other path utilities.

    Returns CountNodeDefinition

createActionCache

createBehavior

createCacheActionQueueItem

createCacheEntry

createCachedAction

createCaller

  • Creates a new instance of a createCaller node, which is a type of a NodeDefinition used inside the query node when requesting Muster to return a function that can be used to imperatively invoke a Muster action. This node is extensively used by Muster React to create callback functions for muster actions. It is intended to be used by any other libraries integrating Muster. The caller function automatically un-wraps the returned value with the use of the valueOf helper.

    example

    Create an action caller

    import muster, { action, createCaller, query, root } from '@dws/muster';
    
    const app = muster({
      addFive: action((number) => number + 5),
    });
    
    const queryResult = await app.resolve(query(root(), {
      addFive: createCaller('addFive'),
    }));
    // queryResult === {
    //   addFive: function(number) {...},
    // },
    
    const result = await queryResult.addFive(3);
    // result === 8

    This example shows how to use the createCaller to retrieve a function that can be used to imperatively invoke Muster actions.

    Parameters

    Returns CreateCallerNodeDefinition

createCallerFunction

createChildPathContext

createChildScope

  • createChildScope(parent: Scope, options?: undefined | object): Scope

createContext

createEmptyDisposeEmitter

  • createEmptyDisposeEmitter(): (Anonymous function)

createEmptyDisposeEmitter

  • createEmptyDisposeEmitter(): (Anonymous function)

createEvent

createEventSource

createFieldResolver

createGraphAction

createGraphNode

createGraphOperation

createHashSet

createHasherFactory

createId

  • createId(): string

createItemPlaceholderFromResult

createMatcher

  • createMatcher<T, P>(name: string, match: function, options?: P | undefined): Matcher<T, P>
  • Type parameters

    • T

    • P

    Parameters

    • name: string
    • match: function
        • (value: any): boolean
        • Parameters

          • value: any

          Returns boolean

    • Default value options: P | undefined = undefined

    Returns Matcher<T, P>

createMigration

createMigrationTester

  • createMigrationTester(migration: Migration): (Anonymous function)

createMigrator

createModule

  • A helper function used when creating a self-contained module. The module can declare its requirements, which will have to be satisfied at the time of the module instantiation. This function returns a module factory function. The factory function expects an object, that fulfils all of the declared module requirements.

    The module has no access to the graph outside of the module. It can only access its own contents and the declared dependencies. It behaves very similar to the scope (it is based on that node).

    example

    Simple module

    import muster, { createModule, ref } from '@dws/muster';
    
    // No requirements, just the module
    const userModule = createModule({}, () => ({
      name: 'Bob',
      age: 29,
    }));
    
    const app = muster({
      user: userModule({}),
    });
    
    await app.resolve(ref('user', 'name'));
    // === 'Bob'
    
    await app.resolve(ref('user', 'age'));
    // === 29

    This example shows how to create a very basic module with no requirements. Such module, when added to the muster graph, can be addressed just like any other graph node.

    example

    Injecting dependencies

    import muster, { computed, createModule, ref } from '@dws/muster';
    
    const userModule = createModule({
      userId: true,
    }, ({ userId }) => ({
      firstName: computed([userId], (resolvedUserId) => `First name ${resolvedUserId}`),
      lastName: computed([userId], (resolvedUserId) => `Last name ${resolvedUserId}`),
    }));
    
    const app = muster({
      currentUserId: 1,
      user: userModule({
        userId: ref('currentUserId'),
      }),
    });
    
    await app.resolve(ref('user', 'firstName'));
    // === 'First name 1'
    
    await app.resolve(ref('user', 'lastName'));
    // === 'Last name 1'

    This example shows how to create a module that has a requirement. This requirement is then satisfied using a ref to a currentUserId.

    Parameters

    Returns ModuleFactory

createMusterScenarioBuilder

createNodeCache

createNodeCacheEntry

createNodeDefinition

createNodeExecutionContext

createNodeType

createOperationComposer

createOperationType

createPredicateFunction

createQueryStream

createQueue

  • createQueue<T>(item?: T): Queue<T>

createQueueItem

createQueuedAction

createRootContext

createRunner

createScope

  • createScope(options?: undefined | object): Scope

createScopeCache

createSetter

  • Creates a new instance of a createSetter node, which is a type of a NodeDefinition used inside the query when requesting Muster to return a function that can be used to imperatively set a Muster variable. This node is extensively used by Muster React to create setter functions. It is intended to be used by any other libraries integrating Muster. The setter function automatically un-wraps a returned value with the use of the valueOf helper.

    example

    Create a setter

    import muster, { createSetter, query, ref, root, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
    });
    
    const queryResult = await app.resolve(query(root(), {
      setName: createSetter('name'),
    }));
    // queryResult === {
    //   setName: function(val) {...},
    // },
    
    const result = await queryResult.setName('Jane');
    // result === 'Jane'
    
    const name = await app.resolve(ref('name'));
    // name === 'Jane'

    This example shows how to use the createSetter to retrieve a function that can be used to imperatively set Muster variables.

    Parameters

    Returns CreateSetterNodeDefinition

createSetterFunction

createStack

  • createStack<T>(): Stack<T>

createStore

createStore

createStream

  • createStream<T>(factory: function): Stream<T>

createSubscription

Const date

  • date(value: Date): string

debug

  • Creates a new instance of a debug node, which is a type of NodeDefinition that can be useful when debugging an application. This node can be used as a wrapper for any node and will trigger the JS debugger breakpoint when the wrapped node is evaluated. Additionally, the output of the node will be logged to the console.

    example

    Debug a computed node

    import muster, { computed, debug } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(debug(computed([], () => {
      console.log('Evaluating the computed');
      return 2;
    })));
    
    // Console output:
    // Evaluating the computed
    // { input: <<computed node json>>, output: { $type: 'value', value: 2 } }

    Running this code will cause a JS debugger breakpoint to be triggered after evaluating the computed node. Note the order of the messages in the console output.

    Parameters

    Returns DebugNodeDefinition

decorateMatcher

  • decorateMatcher(func: any): function

decrement

defaultFallbackGenerator

defaultFallbackGenerator

defaultFallbackGenerator

defaultFallbackGenerator

defer

  • defer<T>(factory: function): Stream<T>

defer

deprecated

  • deprecated(options: object): function

descending

deserialize

deserializeGraphOperation

deserializeMusterType

deserializeNode

deserializeNodeProperties

deserializeOperationProperties

deserializeResponse

deserializeValue

dispatch

  • Creates a new instance of a dispatch node, which is a type of NodeDefinition used to dispatch a Muster event. The event consists of type (which can be a string or a symbol) and an optional payload. The dispatched event can be received by any NodeDefinition in a particular scope. By default, events do not cross scope boundaries. See the scope documentation to learn more about scopes and how to re-dispatch events to a different scope.

    Out of the box, Muster comes with two graph nodes that use events dispatched by the dispatch:

    Additionally, each NodeType can implement its own way of handling events.

    example

    Dispatching an event

    import muster, { dispatch, on, ref, value } from '@dws/muster';
    
    const app = muster({
      isOnline: on((event) => {
        if (event.type === 'online') {
          console.log('Received the `online` event');
          return value(true);
        }
        if (event.type === 'offline') {
          console.log('Received the `offline` event');
          return value(false);
        }
        return undefined;
      }, true),
    });
    
    app.resolve(ref('isOnline')).subscribe((isOnline) => {
      console.log(isOnline ? "Online" : "Offline");
    });
    
    console.log('Dispatch offline');
    await app.resolve(dispatch('offline'));
    
    console.log('Dispatch online');
    await app.resolve(dispatch('online'));
    
    // Console output
    // Online
    // Dispatch offline
    // Offline
    // Dispatch online
    // Online

    This example shows how to use the dispatch to dispatch muster events.

    example

    Scope limited event dispatching

    import muster, { dispatch, key, on, query, root, scope, value } from '@dws/muster';
    
    const app = muster({
      listener: on((event) => {
        if (event.type !== 'event-name') return;
        console.log('Received `event-name` in the root scope');
      }, 'initial'),
      innerScope: scope({
        listener: on((event) => {
          if (event.type !== 'event-name') return;
          console.log('Received `event-name` in the inner scope');
        }, 'initial inner'),
      }),
    });
    
    // Subscribe to both root-scope listener and inner-scope listener
    app.resolve(query(root(), {
      listener: key('listener'),
      innerScope: key('innerScope', {
        listener: key('listener'),
      }),
    })).subscribe(() => {});
    
    console.log('Dispatching the event');
    await app.resolve(dispatch('event-name'));
    
    // Console output:
    // Dispatching the event
    // Received `event-name` in the root scope

    This example shows that the events are locked to a single scope. By default, the events do not cross the scope boundary. This behaviour can be selectively changed. Each scope can define its own event re-dispatching policy.

    example

    Re-dispatching events to child scopes

    import muster, { dispatch, key, on, query, root, scope } from '@dws/muster';
    
    const app = muster({
      listener: on((event) => {
        if (event.type === 'first-event') {
          console.log('Received `first-event` in the root scope');
        }
        if (event.type === 'second-event') {
          console.log('Received `second-event` in the root scope');
        }
      }, 'initial'),
      innerScope: scope({
        listener: on((event) => {
          if (event.type === 'first-event') {
            console.log('Received `first-event` in the inner scope');
          }
          if (event.type === 'second-event') {
            console.log('Received `second-event` in the inner scope');
          }
        }, 'initial inner'),
      }, {}, (event) => event.type === 'first-event' ? event : undefined),
    });
    
    // Subscribe to both root-scope listener and inner-scope listener
    app.resolve(query(root(), {
      listener: key('listener'),
      innerScope: key('innerScope', {
        listener: key('listener'),
      }),
    })).subscribe(() => {});
    
    console.log('Dispatching the `first-event`');
    await app.resolve(dispatch('first-event'));
    
    console.log('Dispatching the `second-event`');
    await app.resolve(dispatch('second-event'));
    
    // Console output:
    // Dispatching the `first-event`
    // Received `first-event` in the root scope
    // Received `first-event` in the inner scope
    // Dispatching the `second-event`
    // Received `second-event` in the root scope

    This example shows how to use the selective event re-dispatching. In this example only the events with type 'first-event' are re-dispatched in the child scope. Optionally, instead of the function you can just set the event re-dispatching to true. This means that every event should be re-dispatched.

    Parameters

    Returns DispatchNodeDefinition

disposeCachedNode

disposeCachedScope

disposeChildren

disposeScope

divide

  • Creates a new instance of a divide node, which is a type of NodeDefinition used to divide number-based values.. The divide node takes any number of operands. It will throw an error if the number of operands is below 2 as it doesn't make sense to do the division operation with a single operand.

    example

    Divide by two

    import muster, { divide, ref } from '@dws/muster';
    
    const app = muster({
      eight: 8,
      two: 2,
    });
    
    const result = await app.resolve(
      divide(ref('eight'), ref('two')),
    );
    // result === 4

    This example shows how to divide with the use of divide node.

    example

    Divide five numbers

    import muster, { add, computed, divide, ref, variable } from '@dws/muster';
    
    const app = muster({
      twelve: 12,
      four: computed([], () => 4),
      three: variable(3),
      two: add(ref('one'), ref('one')),
      one: 1,
    });
    
    const result = await app.resolve(
      divide(ref('twelve'), ref('four'), ref('three'), ref('two'), ref('one')),
    );
    // result === 0.5

    This example shows how to divide five differently computed numbers. As mentioned in the description above, this node can handle any number of operands as long as they resolve to a numeric value.

    Parameters

    Returns DivideNodeDefinition

doHttpRequest

doSingleHttpRequest

done

downgradeGraph

empty

  • empty(value: undefined): string

emptyItem

endsWith

  • Creates a new instance of a endsWith node, which is used when checking if a value containing a string ends with a given pattern. The node expects the subject to be a value that contains a string value.

    example

    Check if string ends with a pattern

    import muster, { endsWith } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(endsWith('Hello world', 'rld'));
    // === true
    
    await app.resolve(endsWith('Hello world', 'abc'));
    // === false

    Parameters

    Returns EndsWithNodeDefinition

entries

eq

  • Creates a new instance of an eq node, which is used when comparing values of two other graph nodes. It resolves to value(true) when the values are equal (using the strict equality operator) or to value(false) when they're not equal.

    Both operands of the eq must resolve to a value. It will throw an error if either one of them does not resolve to a value.

    example

    Comparing values

    import muster, { computed, eq } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(eq(1, 1)) // === true
    await app.resolve(eq(123, 321)) // === false
    await app.resolve(eq('1', 1)) // === false
    await app.resolve(eq('Hello world', 'Hello world')) // === true
    await app.resolve(eq(computed([], () => 123), 123)) // === true
    await app.resolve(eq('test 1', 'test 2')) //=== false

    Parameters

    Returns EqNodeDefinition

error

  • Creates a new instance of an error node, which is a type of NodeDefinition used by Muster when an error has occurred. This node contains following information:

    • error - the instance of the caught exception
    • data - additional data provided at the time of error's creation
    • path - path in the graph that caused this error
    • remotePath - path in the remote graph that caused this error

    Every exception raised in Muster is caught and converted to this NodeDefinition. It allows for more fine-grained control of what to do when an error has occurred. Like the pending, the error is usually short-circuited and returned to the subscriber.

    Muster also comes with a helper node that allows catching errors and replacing them with a fallback value. See the ifError documentation to learn more.

    example

    Error short-circuiting

    import muster, { computed, ref } from '@dws/muster';
    
    const app = muster({
      throwError: computed([], () => {
        console.log('Throwing an error');
        throw new Error('Boom!');
      }),
      computeSomething: computed([ref('throwError')], (val) => {
        console.log('Computing something');
        return val + 1;
      }),
    });
    
    const result = await app.resolve(ref('computeSomething'));
    // result === new Error('Boom!')
    // result.path === ['throwError']
    console.log('End');
    
    // Console output:
    // Throwing an error
    // End

    This example shows how the short-circuiting mechanism works. Note that computeSomething does not log anything, as the content of the node is never run. This prevents the application from getting into an inconsistent state.

    example

    Returning a custom error

    import muster, { computed, error, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      age: variable(25),
      spirits: computed([ref('age')], (age) => {
        if (age < 18) {
          return error('Alcohol cannot be sold to people under 18!');
        }
        return ['Beer', 'Gin', 'Whisky', 'Wine'];
      }),
    });
    
    console.log('Subscribing to spirits');
    app.resolve(ref('spirits')).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Changing age to 17')
    await app.resolve(set('age', 17));
    
    // Console output:
    // Subscribing to spirits
    // ['Beer', 'Gin', 'Whisky', 'Wine']
    // Changing age to 17
    // new Error('Alcohol cannot be sold to people under 18!')

    This example shows how to report custom errors from muster. They obey the same rules as internally reported errors. The console output misses one fact that the error in an actual Error object, which contains a stack trace.

    Parameters

    Returns ErrorNodeDefinition

evaluateOperation

extend

  • Creates a new instance of a extend node, which is a type of a NodeDefinition used when extending a branch with additional nodes. It can be compared to Object.assign but for branches.

    example

    Extend an existing branch

    import muster, { extend, key, query, ref, tree, value } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'Bob',
        lastName: 'Roberson',
      },
      extendedUser: extend(
        ref('user'),
        tree({
          age: value(29),
        }),
      ),
    });
    
    const user = await app.resolve(query(ref('extendedUser'), {
      firstName: key('firstName'),
      lastName: key('lastName'),
      age: key('age'),
    }));
    // user = {
    //   firstName: 'Bob',
    //   lastName: 'Roberson',
    //   age: 29,
    // }

    This example shows how to use the extend to add additional nodes to an existing branch.

    Parameters

    Returns ExtendNodeDefinition

extractDependencies

factory

  • Creates a new instance of a factory node, which is a A type of NodeDefinition used when there's a need to delay the creation of a node. The factory creates the instance of the node only when the application tries resolving the factory.

    example

    Using factory node

    import muster, { factory, ref, value } from '@dws/muster';
    
    const app = muster({
      name: factory(() => {
        console.log('Returning name');
        return value('Bob');
      }),
    });
    
    console.log('Retrieving name');
    const result = await app.resolve(ref('name'));
    // result === 'Bob'
    
    // Console output:
    // Retrieving name
    // Returning name

    This example shows how to use the factory to delay the time of the creation of a particular node/branch.

    Parameters

    Returns FactoryNodeDefinition

fetchItems

  • Creates a new instance of the fetchItems node. This node can be used to create collection transform boundaries by making sure that the transforms sent to the fetchItems node get run only after the target gets fully resolved.

    example

    Map transform that returns a computed node

    import muster, {
      applyTransforms,
      computed,
      entries,
      extend,
      fetchItems,
      fromStreamMiddleware,
      get,
      key,
      map,
      query,
      proxy,
      ref,
    } from '@dws/muster';
    
    const remoteInstance = muster({
      people: [
        { firstName: 'Bob', lastName: 'Smith' },
        { firstName: 'Jane', lastName: 'Jonson' },
        { firstName: 'Sabine', lastName: 'Summers' },
      ],
    });
    
    const app = muster({
      remote: proxy([
        fromStreamMiddleware((req) => remoteInstance.resolve(req, { raw: true })),
      ]),
      peopleWithFullNames: applyTransforms(
        fetchItems(ref('remote', 'people')),
        [
          map((user) => extend(user, {
            fullName: computed(
              [get(user, 'firstName'), get(user, 'lastName')],
              (first, last) => `${first} ${last}`,
            ),
          })),
        ],
      ),
    });
    
    await app.resolve(query(ref('peopleWithFullNames'), {
      fullName: key('fullName')
    })); // === [{ fullName: Bob Smith'' }, { fullName: 'Jane Jonson' }, { fullName: 'Sabine Summers' }]

    This example shows how to use a fetchItems to create a boundary for transforms. Note that the peopleWithFullNames node uses a map with a computed node, which can't be serialised and sent over to the remote instance of muster. For this reason we have to wrap the remote collection in a fetchItems node.

    Parameters

    Returns FetchItemsNodeDefinition

fetchValue

fields

  • Creates a new instance of a fields node, which is a type of a NodeDefinition used inside of a query to represent a nested graph structures. It serves as a container for a following graph nodes:

    Muster is performing implicit conversion to this node type every time a query or a key node with fields is created.

    example

    Implicit conversion in query

    import { fields, key, query, root } from '@dws/muster';
    
    query(root(), {
      firstName: key('firstName'),
      lastName: key('lastName'),
    });
    // is equivalent to
    query(root(), fields({
      firstName: key('firstName'),
      lastName: key('lastName'),
    }));

    This example shows how Muster implicitly converts an object to a fields when creating a query with child fields.

    example

    Implicit conversion in key

    import { fields, key } from '@dws/muster';
    
    key('someKey', {
      firstName: key('firstName'),
      lastName: key('lastName'),
    });
    // is equivalent to
    key('someKey', fields({
      firstName: key('firstName'),
      lastName: key('lastName'),
    }));

    This example shows how Muster implicitly converts an object to a fields when creating a key with child fields.

    example

    Implicit conversion in entries

    import { fields, key, entries } from '@dws/muster';
    
    entries({
      firstName: key('firstName'),
      lastName: key('lastName'),
    });
    // is equivalent to
    entries(fields({
      firstName: key('firstName'),
      lastName: key('lastName'),
    }));

    This example shows how Muster implicitly converts an object to a fields when creating an entries with child fields.

    Parameters

    Returns FieldsNodeDefinition

filter

  • filter<T>(predicate: function, stream: Stream<T>): Stream<T>

filter

  • Creates a new instance of a filter node, which is a type of collection transform used to filter the items returned from a collection using a given predicate. The predicates are constructed from muster logic nodes. These nodes include:

    example

    Simple filters

    import muster, { applyTransforms, filter, gt, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: applyTransforms(
        [1, 2, 3, 4, 5],
        [filter((item) => gt(item, 2))],
      ),
    });
    
    const filteredNumbers = await app.resolve(query(ref('numbers'), entries()));
    // filteredNumbers === [3, 4, 5]

    This example shows how to apply a filter to a collection. The predicate from this example uses a gt node for filtering items that are greater than 2. See the gt documentation for more information.

    example

    Applying filters in a query

    import muster, { filter, lt, entries, query, ref, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const filteredNumbers = await app.resolve(query(ref('numbers'), withTransforms([
      filter((item) => lt(item, 4)),
    ], entries())));
    // filteredNumbers === [1, 2, 3]

    This example shows how to apply a filter to a collection from within a query node. The filter predicate uses a lt node to filter the items with a value of less than 4.

    example

    Filtering based on properties

    import muster, { applyTransforms, filter, gt, entries, key, query, ref } from '@dws/muster';
    
    const app = muster({
      books: applyTransforms(
        [
          { title: 'Casino Royale', author: 'Ian Fleming', year: 1953 },
          { title: 'Live and Let Die', author: 'Ian Fleming', year: 1954 },
          { title: 'The Big Four', author: 'Agatha Christie', year: 1927 },
        ],
        [
          filter((book) => gt(ref({ root: book, path: 'year' }), 1930)),
        ],
      ),
    });
    
    const booksAfter1930 = await app.resolve(query(ref('books'), entries({
      title: key('title'),
    })));
    // booksAfter1930 === [
    //   { title: 'Casino Royale' },
    //   { title: 'Live and Let Die' },
    // ]

    This example shows how to filter items based on a property value. It uses a ref node to change the starting point of the reference, as opposed to using the root of the graph as the staring point (note the assignment root: book). Next comes the path to the property to retrieve. In this example, the path is just a string, but you can also provide an array containing a full path to a target property.

    example

    Complex filters

    import muster, { and, applyTransforms, entries, filter, gt, key, lt, query, ref } from '@dws/muster';
    
    const app = muster({
      books: applyTransforms(
        [
          { title: 'Casino Royale', author: 'Ian Fleming', year: 1953 },
          { title: 'Live and Let Die', author: 'Ian Fleming', year: 1954 },
          { title: 'The Big Four', author: 'Agatha Christie', year: 1927 },
          { title: 'The Martian', author: 'Andy Weir', year: 2011 },
        ],
        [
          filter((book) => and(
            gt(ref({ root: book, path: 'year' }), 1930),
            lt(ref({ root: book, path: 'year' }), 2000),
          )),
        ],
      ),
    });
    
    const booksBetween1930and2000 = await app.resolve(query(ref('books'), entries({
      title: key('title')
    })));
    // booksBetween1930and2000 === [
    //   { title: 'Casino Royale' },
    //   { title: 'Live and Let Die' },
    // ]

    This example shows how to create complex queries with an and node. These nodes can be nested indefinitely.

    example

    Accessing the graph from filters

    import muster, {
      and,
      applyTransforms,
      entries,
      filter,
      gt,
      key,
      lt,
      query,
      ref,
      variable,
    } from '@dws/muster';
    
    const app = muster({
      minYear: variable(1930),
      maxYear: variable(2000),
      books: applyTransforms(
        [
          { title: 'Casino Royale', author: 'Ian Fleming', year: 1953 },
          { title: 'Live and Let Die', author: 'Ian Fleming', year: 1954 },
          { title: 'The Big Four', author: 'Agatha Christie', year: 1927 },
          { title: 'The Martian', author: 'Andy Weir', year: 2011 },
        ],
        [
          filter((book) => and(
            gt(ref({ root: book, path: 'year' }), ref('minYear')),
            lt(ref({ root: book, path: 'year' }), ref('maxYear')),
          )),
        ],
      ),
    });
    
    const booksBetween1930and2000 = await app.resolve(query(ref('books'), entries({
      title: key('title')
    })));
    // booksBetween1930and2000 === [
    //   { title: 'Casino Royale' },
    //   { title: 'Live and Let Die' },
    // ]

    This example shows that filters don't have to be static: they can also access data from the muster graph. Building on the previous example, this example replaces the hard-coded min and max release dates with the references to variables.

    Parameters

    Returns FilterNodeDefinition

  • Parameters

    Returns FilterNodeDefinition

findBranchByKey

first

  • Creates a new instance of the first node, which can be used as part of a ref to request a first item of a given collection.

    example

    Get first primitive item from a collection

    import muster, { first, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3],
    });
    
    await app.resolve(ref('numbers', first())); // === 1

    This example shows how to get the first item from the collection, when the collection contains only primitive items.

    example

    Query the first item from a collection

    import muster, { first, key, query, ref } from '@dws/muster';
    
    const app = muster({
      people: [
        { firstName: 'Bob', lastName: 'Smith' },
        { firstName: 'Jane', lastName: 'Jonson' },
        { firstName: 'Sabine', lastName: 'Summers' },
      ],
    });
    
    await app.resolve(query(ref('people', first()), {
      firstName: key('firstName'),
      lastName: key('lastName'),
    })); // === { firstName: 'Bob', lastName: 'Smith' }

    This example shows how to get the first item from the collection, when the collection contains tree nodes.

    Returns FirstNodeDefinition

firstErrorOrToNodeDefinitionArray

firstItem

  • Creates a new instance of a firstItem node, which is a type of collection transform used when taking the first item out of a collection. This node serves as a fast implementation of the take(1). It also comes with a shorthand version to be used in the ref. See the References to items in collections example from the ref documentation.

    example

    Take first item (using transform)

    import muster, { entries, firstItem, query, ref, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const item = await app.resolve(query(ref('numbers'), withTransforms([
      firstItem(),
    ], entries())));
    // item === [1]

    This example shows how to use a firstItem transform to take the first item out of a collection.

    Returns FirstItemNodeDefinition

flatMap

flatten

flattenQuerySetChildren

floor

  • Creates a new instance of a floor node, which is a type of a NodeDefinition used when converting a number (int or float) to a largest integer lower or equal to the current number. It works in the same way as the Math.floor from JavaScript.

    example

    Floor the value

    import muster, { floor, ref } from '@dws/muster';
    
    const app = muster({
      fivePointThree: 5.3,
    });
    
    await app.resolve(floor(5));
    // === 5
    
    await app.resolve(floor(5.2));
    // === 5
    
    await app.resolve(floor(ref('fivePointThree')));
    // === 5

    Parameters

    Returns FloorNodeDefinition

flow

  • Creates a new instance of the flow node, which works similarly to the flow function from lodash, and can be used to chain node calls.

    example

    Using the flow node

    import muster, { call, flow, format, fn, ref, setResult, variable } from '@dws/muster';
    
    const app = muster({
      createArticle: fn(() =>
        // The logic to create article goes here
        // And then return article id
        value('article-id')
      ),
      url: variable('/'),
    });
    
    console.log('Get the URL');
    app.resolve(ref('url')).subscribe((url) => console.log('URL:', url));
    
    console.log('Call flow node');
    await app.resolve(call(flow(
      ref('createArticle'),
      fn((id) => setResult('url', format('/article/${id}', { id }))),
    )));
    
    // Console output:
    // Get the URL
    // URL: /
    // Call flow node
    // URL: /article/article-id

    Parameters

    Returns FlowNodeDefinition

flush

  • flush(store: Store): void

flushInvalidations

  • flushInvalidations(store: Store): void

fn

  • Creates a new instance of a fn node, which is a type of a NodeDefinition used for representing executable functions implemented with muster NodeDefinitions. These functions are safely serializable and can be executed on a remote muster instances.

    The fn is being used by the collection transforms to represent filters and other types of collection transforms.

    The fn can be executed with the help of call and apply.

    example

    Create a simple fn

    import { fn, value } from '@dws/muster';
    
    fn(() => value(true));

    This example shows how to create a very basic fn that simply returns a true value ever time it gets called.

    example

    Create an fn with args

    import { add, fn } from '@dws/muster';
    
    fn((num) => add(num, 5));

    This example shows how to create an fn capable of adding 5 to an argument.

    example

    Calling an fn

    import muster, { add, call, fn } from '@dws/muster';
    
    const app = muster({
      addFive: fn((num) => add(num, 5)),
    });
    
    await app.resolve(call('addFive', [3]));
    // === 8

    This example shows how to call an fn. See the call and apply documentation to learn more about calling callable nodes.

    example

    Create an fn with named args

    import muster, { call, fn, format } from '@dws/muster';
    
    const app = muster({
      greet: fn(['name'], ({ name }) =>
        format('Hello, ${name}!', { name })
      ),
    });
    
    await app.resolve(call('greet', { name: 'Bob' }));
    // === 'Hello, Bob!'

    This example shows how to create and call an fn node with named arguments.

    Parameters

    Returns FnNodeDefinition

  • Parameters

    Returns FnNodeDefinition

format

  • Creates a new instance of a format node, which is used converting a values of objects to string and inserts them into another string. It uses the same syntax as the Format Literals from JavaScript.

    example

    Simple format string

    import muster, { ref, format } from '@dws/muster';
    
    const app = muster({
      name: 'Bob',
    });
    
    const greeting = await app.resolve(format('Hello, ${name}', {
      name: ref('name'),
    }));
    // === 'Hello, Bob'

    This example shows how to use the format to create a string from a given format and a value of a graph node.

    Parameters

    Returns FormatNodeDefinition

formatError

formatErrorNode

formatPath

  • formatPath(path: Array<ChildKey>): string

fromBase64

  • Creates a new instance of a fromBase64 node, which is used when converting a base64 encoded string back to a normal string. The node expects the subject to be a value that contains a string value.

    example

    Convert the string back from Base64

    import muster, { fromBase64 } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(fromBase64('SGVsbG8gd29ybGQ='));
    // === 'Hello world'

    This example shows how to convert a base 64 encoded string to a string.

    Parameters

    Returns FromBase64NodeDefinition

fromEmitter

  • fromEmitter<T>(emitter: object): Stream<T>

fromPromise

  • Creates a new instance of fromPromise node, which is a type of NodeDefinition useful when integrating asynchronous code with muster. This node can be used when making API requests from within muster code. These requests may retrieve or update data from a remote service.

    The fromPromise allows for handling set requests through a set. See the "Handling set requests" example for more information.

    example

    Basic promise node

    import muster, { fromPromise, ref } from '@dws/muster';
    
    const app = muster({
      asyncName: fromPromise(() => Promise.resolve('async name')),
    });
    
    // Resolving with 'await'
    const awaitName = await app.resolve(ref('asyncName'));
    // awaitName === 'async name'
    
    // Resolving with streams
    let streamName = 'initial';
    app.resolve(ref('asyncName')).subscribe((name) => {
      // name === 'async name'
      // streamName === 'initial'
      streamName = name;
      // streamName === 'async name'
    });
    // streamName === 'initial'

    This example demonstrates the asynchronous nature of fromPromise. When the ref is requested with await it forces the code to wait for the fromPromise to emit a value. Internally Muster requires every NodeDefinition to emit its value synchronously. To get around that, fromPromise initially returns a pending, then an updated value when the promise resolves.

    The reason why in the example code the pending isn't emitted to the "outside world" is that these values are internal to muster and are filtered out before returning the response.

    example

    Promise factory params

    import muster, { fromPromise, match, ref, tree, types, value } from '@dws/muster';
    
    const app = muster({
      user: {
        [match(types.string, 'id')]: fromPromise(({ id }) =>
          // You could make a request to an API endpoint here...
          Promise.resolve(tree({
            id: value(id),
            name: value(`User ${id}`),
          })),
        ),
      },
    });
    
    const user1Name = await app.resolve(ref('user', '1', 'name'));
    // user1Name === 'User 1'
    
    const user2Name = await app.resolve(ref('user', '2', 'name'));
    // user2Name === 'User 2'

    This example demonstrates a real-world case of requesting user data based on their ID. Note the promise factory in fromPromise receives a parameter with one field: id.

    example

    Implementing set promise factory

    import muster, { fromPromise, ref, set, tree } from '@dws/muster';
    
    const userSettings = {
      homepage: 'https://www.db.com',
    };
    
    const app = muster({
      homepage: fromPromise({
        // Make an API request instead
        get: () => Promise.resolve(userSettings.homepage),
        // Make an API request instead
        set: (params, newValue) => new Promise((resolve) => {
          userSettings.homepage = newValue;
          resolve();
        }),
      }),
    });
    
    let setTriggered = false;
    
    // Subscribe to the 'homepage'
    console.log('Requesting homepage');
    app.resolve(ref('homepage')).subscribe((homepage) => {
      console.log(`Homepage: ${homepage}`);
      !setTriggered && triggerSet();
    });
    
    async function triggerSet() {
      setTriggered = true;
      console.log('Setting homepage');
      await app.resolve(set('homepage', 'https://wwww.github.com'));
    }
    
    // Console output:
    // Requesting homepage
    // Homepage: https://www.db.com
    // Setting homepage
    // Homepage: https://www.github.com

    Parameters

    Returns FromPromiseNodeDefinition

fromStream

  • Creates an instance of a fromStream node, which is a type of NodeDefinition that allows plugging streams/observables into Muster. This node will emit new values every time the underlying stream emits. The fromStream opens the subscription to the source stream only when subscribed to. It also unsubscribes from the source stream when all subscriptions to this graph node are closed.

    The fromStream works with any stream library that conforms to the Observable API. Examples of libraries that should work with the fromStream:

    example

    Simple stream

    import { BehaviorSubject } from '@dws/muster-observable';
    import muster, { fromStream, ref, value } from '@dws/muster';
    
    const subject = new BehaviorSubject(value('initial'));
    const app = muster({
      myStreamedValue: fromStream(subject),
    });
    
    app.resolve(ref('myStreamedValue')).subscribe((res) => {
      console.log(res);
    });
    
    subject.next(value('updated'));
    
    // Console output:
    // initial
    // updated

    This example shows how to plug a Behaviour Subject into Muster. Note that in the subscribe callback the res is a value. The fromStream automatically wraps the value returned from the stream with a value node.

    example

    Connecting two instances of Muster

    import muster, { fromStream, ref, set, variable } from '@dws/muster';
    
    const otherApp = muster({
      name: variable('initial'),
    });
    
    const app = muster({
      remoteName: fromStream(otherApp.resolve(ref('name'))),
    });
    
    app.resolve(ref('remoteName')).subscribe((res) => {
      console.log(res);
    });
    
    await otherApp.resolve(set('name', 'updated'));
    
    // Console output:
    // initial
    // updated

    Because the output value of the muster.resolve also conforms to the Observable API, you can create connections between two instances of Muster. This is not a recommended way of making that connection. It only serves as an example how to handle different kinds of streams.

    Parameters

    Returns FromStreamNodeDefinition

fromStreamMiddleware

fuzzyTraverse

generateFlushEvents

generateMatcherKey

  • generateMatcherKey(predicate: KeyMatcher, param: string | undefined): string

generateUniqueContextVariableName

  • generateUniqueContextVariableName(name: string): string

get

  • Creates a new instance of the get node, which is a node used for traversing a graph. It can be used for getting child node from a given "container-like" node. It's used internally by ref.

    Muster has a number of nodes which can be considered "container-like" nodes: tree, placeholder, extend, etc.

    example

    Getting a child from a branch

    import muster, { get, tree, value } from '@dws/muster';
    
    const app = muster({
      name: 'from muster graph',
    });
    
    const name = await app.resolve(get(
      tree({ name: value('from test branch') }),
      value('name'),
    ));
    // name === 'from test branch'

    gets operate in the context of a given root node. In this example we've chosen a new tree to be our root node.

    If you want to access the name from the root of the muster graph, you can use a special type of NodeDefinition: root. See the "Using root node" example for more information.

    example

    Using the root node

    import muster, { get, root, value } from '@dws/muster';
    
    const app = muster({
      name: 'from muster graph',
    });
    
    const name = await app.resolve(get(root(), value('name')));
    // name === 'from muster graph'
    example

    Nesting get nodes

    import muster, { get, root, value } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'Bob',
      },
    });
    
    const firstName = await app.resolve(
      get(
        get(root(), value('user')),
        value('firstName'),
      ),
    );
    // firstName === 'Bob'
    // These nested get nodes are equivalent to: ref('user', 'firstName')

    Because the root of the get can be any NodeDefinition, one can make nested gets - the result of the inner get is used as the root of the outer.

    As this syntax is a bit clunky, Muster includes a ref to help..

    Parameters

    Returns GetNodeDefinition

getActionCache

getBranchByName

getBranchNames

getCachedAction

getChildEventSource

getChildOperation

getComparator

getContextDependencies

getContextDependencies

getContextPathKey

getContextValues

getCustomHeaders

getDependencies

getDependenciesToResolve

getDependencyValues

getHistoryUpdater

  • getHistoryUpdater(history: History, shouldUpdate?: Boolean): HistoryUpdater

getInitialNodeData

getInitialNodeState

getInstanceOfMatcher

  • getInstanceOfMatcher(type: Function): function
  • Parameters

    • type: Function

    Returns function

      • (value: any): boolean
      • Parameters

        • value: any

        Returns boolean

getInvalidTypeError

getInvalidTypeErrorMessage

getIsCacheable

getItemId

  • getItemId(node: GraphNode): string | undefined

getItems

getItemsOperation

getMatcherKeyId

  • getMatcherKeyId(name: string): string | undefined

getMatcherName

  • getMatcherName(value: any): string

getMatcherOptions

  • getMatcherOptions<T, P>(matcher: Matcher<T, P>): P

getMatcherType

getMaxStackDepthErrorMessage

  • getMaxStackDepthErrorMessage(message: string, stack: Stack<CachedAction> | undefined, queue: Queue<object>): string

getMissingContextValueErrorMessage

getMusterNodeTypesMap

getMusterOperationTypesMap

getMusterTypesMap

getNextIteratorResult

getNodeActionContextDependencies

getNodeActionDependencies

getNodeActionValue

getNodeCache

getNodeData

getNodeState

getOperationHandler

getOperationHandlerDependency

getOtherOperations

getParamContextId

  • getParamContextId(param: string): string

getParamEncoder

getParams

getParentPathContext

getPath

getPath

  • getPath(object: object, path: Array<string>): any

getPredicate

getProxiedNodeDefinition

getProxiedNodeValue

getQueryBuilderSnapshot

getQuerySetChildForPathPart

getResolvedDependencies

getResolvedValuesOfDependencies

getResolverContext

getScopeCache

getStackErrorMessage

getStackItems

  • getStackItems<T>(stack: Stack<T>): Array<T>

getSubscriptions

getTransformsAndChildrenForEntries

getType

  • getType(value: any): string
  • Get a string representation of a value's type, as used in error messages.

    Parameters

    • value: any

      Value to inspect

    Returns string

    String representation of the value's type

getTypeRecursive

  • getTypeRecursive(value: any, visited: Array<any>): string

graph

graphNode

groupBy

  • Creates a new instance of a groupBy transform, which is a type of collection transform used to group the items by a given predicate. The groupBy node takes a predicate node that needs to implement a call operation (e.g. fn, action). The groupBy transform returns an array of grouped items. Consider a following example:

    muster({
       items: [
         { category: 'vegetable', name: 'carrot' },
         { category: 'fruit', name: 'apple' },
         { category: 'fruit', name: 'plum' },
         { category: 'vegetable', name: 'potato' },
         { category: 'confectionery', name: 'chocolate' },
       ],
       groupedItems: applyTransforms(
         ref('items'),
         [groupBy((item) => get(item, 'category'))],
       ),
     })

    The groupedItems collection has following items:

    array([
      array([
        { category: 'vegetable', name: 'carrot' },
        { category: 'vegetable', name: 'potato' },
      ]),
      array([
        { category: 'fruit', name: 'apple' },
        { category: 'fruit', name: 'plum' },
      ]),
      array([{ category: 'confectionery', name: 'chocolate' }])
    ])

    Parameters

    Returns GroupByNodeDefinition

gt

  • Creates a new instance of a gt node, which checks if a given node's value is greater than the value of another graph node. This comparison is done with the > operator.

    example

    Comparing values

    import muster, { computed, gt } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(gt(5, 4)) // === true
    await app.resolve(gt(5, 5)) // === false
    await app.resolve(gt(5, 6)) // === false
    await app.resolve(gt(computed([], () => 100), 99)) // === true
    await app.resolve(gt(computed([], () => 99), 100)) // === false

    Parameters

    Returns GtNodeDefinition

gte

  • Creates a new instance of a gte node, which is used to check if a given node's value is greater or equal than the value of another graph node. This comparison is done with the >= operator.

    example

    Comparing values

    import muster, { computed, gte } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(gte(5, 4)) // === true
    await app.resolve(gte(5, 5)) // === true
    await app.resolve(gte(5, 6)) // === false
    await app.resolve(gte(computed([], () => 100), 99)) // === true
    await app.resolve(gte(computed([], () => 100), 100)) // === true
    await app.resolve(gte(computed([], () => 100), 101)) // === false

    Parameters

    Returns GteNodeDefinition

handleErrors

handleStep

hasAllContextDependencies

  • hasAllContextDependencies(node: GraphNode): boolean

hasChildOperations

hasMatcherKeyId

  • hasMatcherKeyId(name: string): boolean

hashSetContains

  • hashSetContains(key: string, set: HashSet): boolean

head

  • Creates a new instance of a head node, which is a type of a NodeDefinition used by the get when extracting the first item from the collection. It serves as a helper node that generates a firstItem transform and applies that to the target collection. This node resolves to a single NodeDefinition or a nil when the collection is found to be empty.

    example

    Take first item from the collection

    import muster, { head, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
    });
    
    await app.resolve(head(ref('numbers')));
    // === 1

    This example shows how to use the head node to extract the first item from the array.

    Parameters

    Returns HeadNodeDefinition

hoistDependencies

identity

identityOperation

ifElse

  • Creates a new instance of an ifElse node, which allows creation of conditional expressions. You can think of it as a if ... else ... statement in any programming language. This node by conditionally resolving to then node when the if condition resolves to true; otherwise resolves to else. The if, then and else nodes can be any graph nodes.

    example

    Simple if-else

    import muster, { ifElse, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      isLoggedIn: variable(false),
      greeting: ifElse({
        if: ref('isLoggedIn'),
        then: 'Hello, logged-in user!',
        else: 'Hello, guest!',
      }),
    });
    
    app.resolve(ref('greeting')).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Logging in');
    await app.resolve(set('isLoggedIn', true));
    
    // Console output:
    // Hello, guest!
    // Logging in
    // Hello, logged-in user!

    Parameters

    Returns IfElseNodeDefinition

ifError

  • Creates a new instance of an ifError node, which is a type of NodeDefinition used when implementing something like try ... catch ..., but for nodes. See the error documentation for an introduction to errors.

    The ifError can be used when a node resolves to an error node. You can configure what should happen in that scenario by providing a fallback node or fallback generator function. The fallback node will simply return that node instead of the error. The fallback generator allows for more sophisticated error handling. It takes two arguments:

    example

    Catching error

    import muster, { computed, error, ifError, ref, set, value, variable } from '@dws/muster';
    
    const app = muster({
      age: variable(25),
      spirits: computed([ref('age')], (age) => {
        if (age < 18) {
          return error('Alcohol cannot be sold to people under 18!');
        }
        return ['Beer', 'Gin', 'Whisky', 'Wine'];
      }),
    });
    
    console.log('Subscribing to spirits');
    app.resolve(ifError(value([]), ref('spirits'))).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Changing age to 17')
    await app.resolve(set('age', 17));
    
    // Console output:
    // Subscribing to spirits
    // ['Beer', 'Gin', 'Whisky', 'Wine']
    // Changing age to 17
    // []

    This example builds on the code from error. It wraps the ref to spirits with an ifError to prevent any errors from being returned to the subscriber. It makes sure that the subscriber always receives a value node with array of items.

    example

    Using a fallback generator

    import muster, { computed, error, ifError, ref, set, value, variable } from '@dws/muster';
    
    const app = muster({
      age: variable(25),
      spirits: computed([ref('age')], (age) => {
        if (age < 18) {
          return error('Alcohol cannot be sold to people under 18!', { data: 1 });
        }
        return ['Beer', 'Gin', 'Whisky', 'Wine'];
      }),
    });
    
    console.log('Subscribing to spirits');
    app.resolve(ifError((error) => {
      if (error.properties.data === 1) {
        // It's safe to handle the error with data === 1
        return value([]);
      }
      // Something else has gone wrong, return that error
      return error;
    }, ref('spirits'))).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Changing age to 17')
    await app.resolve(set('age', 17));
    
    // Console output:
    // Subscribing to spirits
    // ['Beer', 'Gin', 'Whisky', 'Wine']
    // Changing age to 17
    // []

    This example shows how to use a fallback generator to catch only specific types of errors. The fallback generator in this example checks if the error received has data equal to 1. If not, it returns the original error.

    example

    Catching action errors

    import muster, { action, call, error, ifError, ref } from '@dws/muster';
    
    const app = muster({
      getGreeting: action((name) => {
        if (!/[A-Za-z]+/.test(name)) {
          return error(`Invalid name: ${name}`);
        }
        return `Hello, ${name}`;
      }),
      getGreetingSafe: ifError('Hello, stranger', ref('getGreeting')),
    });
    
    const bob = await app.resolve(call('getGreeting', ['Bob']));
    // bob === 'Hello, Bob'
    
    const invalid = await app.resolve(call('getGreeting', ['123']));
    // invalid === 'Invalid name: 123'
    
    const bobSafe = await app.resolve(call('getGreetingSafe', ['Bob']));
    // bobSafe === 'Hello, Bob'
    
    const invalidSafe = await app.resolve(call('getGreetingSafe', ['123']));
    // invalidSafe === 'Hello, stranger'

    This example shows how to use the ifError to catch action errors and replace the result with a different one. Just like in the previous example, you could use the fallback generator..

    Parameters

    Returns IfErrorNodeDefinition

ifPending

  • Creates a new instance of a ifPending node, which is a type of a NodeDefinition used when there's a need to always return a value for a certain node even if the target is not resolved (is pending). This node is used by Muster-React to decide whether a certain query is loading. It works in a similar way to the ifError with a difference that the ifError provides a fallback for the error, while this node provides a fallback for the pending.

    The fallback can be either a pre-defined NodeDefinition or a fallback generator. The fallback generator receives a previous value the target was resolved to (undefined if this is the first time target is being resolved) and is expected to return a NodeLike.

    example

    Prevent pending state

    import muster, { fromPromise, ifPending, ref, value } from '@dws/muster';
    
    const app = muster({
      asyncName: fromPromise(() => Promise.resolve('Bob')),
      syncName: ifPending(
        (previous) => previous || value('Loading...'),
        ref('asyncName'),
      ),
    });
    
    app.resolve(ref('syncName')).subscribe((name) => {
      console.log(name);
    });
    
    // Console output:
    // Loading...
    // Bob

    This example shows how to use the ifPending to synchronously return a name. It makes sure that the asyncName node does not block the query.

    Parameters

    Returns IfPendingNodeDefinition

ignore

  • ignore(value: any): string

includes

  • Creates a new instance of a includes node, which is used when checking if a string contains a given pattern. The node expects the subject to be a value that contains a string value.

    example

    Check if a string includes a pattern

    import muster, { includes } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(includes('wor', 'Hello world'));
    // === true
    
    await app.resolve(includes('els', 'Hello world'));
    // === false

    Parameters

    Returns IncludesNodeDefinition

incorrectNodeType

increment

init

injectDependencies

  • Creates a new instance of the injectDependencies node, which can be used when creating partially resolved nodes. This node allows supplying some or all of the context and node dependencies of a given node.

    example

    Call inject dependencies on a computed node - no injected dependencies

    import muster, {
      computed,
      injectDependencies,
      ref,
    } from '@dws/muster';
    
    const app = muster({
      two: 2,
      four: 4,
    });
    
    await app.resolve(injectDependencies(
      computed(
        [ref('four'), ref('two')],
        (left, right) => left * right,
      ),
      [], // Dependencies to override
    )); // === 8

    In this example we have created a computed node with two dependencies:

    • ref('four')
    • ref('two')

    When resolved against the graph above this produces 8. Because in our example we have not overridden any dependencies through the injectDependencies, the node end up resolving to 8 as well.

    example

    Call inject dependencies on a computed node - change both dependencies

    import muster, {
      computed,
      injectDependencies,
      ref,
      value,
    } from '@dws/muster';
    
    const app = muster({
      two: 2,
      four: 4,
    });
    
    await app.resolve(injectDependencies(
      computed(
        [ref('four'), ref('two')],
        (left, right) => left * right,
      ),
      [value(5), value(3)], // Dependencies to override
    )); // === 15

    This example re-uses the code from the previous example with a notable difference of having defined dependency overrides. Note that the values used as overrides are now 5 and 3. Due to the way the computed node is implemented the order of these values matches the order of arguments in the combine function of the computed, meaning that left = 5 and right = 3.

    example

    Call inject dependencies on a computed node - change only the last argument

    import muster, {
      computed,
      injectDependencies,
      ref,
      value,
    } from '@dws/muster';
    
    const app = muster({
      two: 2,
      four: 4,
    });
    
    await app.resolve(injectDependencies(
      computed(
        [ref('four'), ref('two')],
        (left, right) => left * right,
      ),
      [undefined, value(3)], // Dependencies to override
    )); // === 12

    Apart from being able to override all dependencies, injectDependencies node enables the developers with ability to override a specific dependency. In the example code above the first dependency was set to undefined, which tells the injectDependencies node that this is not a real value, and it should resolve it as normally, but the second dependency is defined. This means that the combine function of the computed node is called with left = ref('four') => 4 and right = 3.

    Parameters

    Returns InjectDependenciesNodeDefinition<NodeDefinition>

inspect

instance

instanceOf

  • instanceOf<T, P>(type: P): Matcher<T, P>

invalidate

invalidateCachedAction

  • invalidateCachedAction(store: Store, cachedAction: CachedAction, isInvalidating: boolean): void

invalidateNode

invalidateNodeAction

invalidateOn

  • Creates a new instance of an invalidateOn node, which is a type of NodeDefinition used to trigger the invalidation mechanism. Invalidation causes the target node to lose its value and forces a re-fetch of it. This is particularly useful for nodes like fromPromise or computed that can change the value depending on some external factors e.g. calling an API endpoint or some local variable in the code (which is not recommended).

    It works similarly to the invalidate with the difference being the mechanism triggering the invalidation. The invalidate causes invalidation when resolved; invalidateOn causes invalidation upon dispatching a specific Muster event. See the dispatch to learn more about dispatching Muster events.

    The predicate for the invalidateOn can be defined as:

    • the type of the triggered event to respond to
    • an array of triggered event types to respond to
    • a function that takes [[EventData]] and returns a boolean
    example

    Invalidating on event

    import muster, { dispatch, fromPromise, invalidateOn, ref } from '@dws/muster';
    
    const externalNumbers = [1, 2, 3];
    
    const app = muster({
      numbers: invalidateOn(
        'invalidate-numbers',
        fromPromise(() => Promise.resolve(externalNumbers)),
      ),
    });
    
    app.resolve(ref('numbers')).subscribe((numbers) => {
      console.log(numbers);
    });
    
    console.log('Adding `4` to numbers`');
    externalNumbers.push(4);
    
    console.log('Dispatching the `invalidate-numbers` event');
    await app.resolve(dispatch('invalidate-numbers'));
    
    // Console output:
    // [1, 2, 3]
    // Adding `4` to numbers`
    // Dispatching the `invalidate-numbers` event
    // [1, 2, 3, 4]

    This example shows how to use the invalidateOn to invalidate a part of the graph when a particular event is triggered.

    Parameters

    Returns InvalidateOnNodeDefinition

isActionNodeDefinition

isAddItemAtOperation

isAddNodeDefinition

isAndNodeDefinition

isApplyNodeDefinition

isArrayListNodeDefinition

isArrayNodeDefinition

isArrayNodeOrPendingNode

  • isArrayNodeOrPendingNode(node: GraphNode): boolean

isBooleanValueNode

  • isBooleanValueNode(node: GraphNode): boolean

isCallArgumentArray

isCallArgumentMap

isCallNodeDefinition

isCallOperation

isCatchErrorNodeDefinition

isCeilNodeDefinition

isCharAtNodeDefinition

isChooseNodeDefinition

isClampNodeDefinition

isClearOperation

isCollectionFieldsNode

  • isCollectionFieldsNode(value: GraphNode): boolean

isCollectionFieldsNodeDefinition

isCollectionFieldsNodeDefinition

isCombineLatestNodeDefinition

isContainsOperation

isContext

  • isContext(value: any): boolean

isContextNodeDefinition

isCreateBehaviorNodeDefinition

isCreateCallerNodeDefinition

isCreateSetterNodeDefinition

isDataNode

isDebugNodeDefinition

isDeferNodeDefinition

isDispatchNodeDefinition

isDivideNodeDefinition

isDoneNodeDefinition

isDynamicNode

isDynamicNodeType

  • isDynamicNodeType(nodeType: NodeType): boolean

isEmptyItemNodeDefinition

isEndsWithNodeDefinition

isEntriesNodeDefinition

isEqNodeDefinition

isErrorNodeDefinition

isEvaluateOperation

isEvent

  • isEvent(value: any): boolean

isExclusiveSliceBounds

  • isExclusiveSliceBounds(value: any): boolean

isExtendNodeDefinition

isFactoryNodeDefinition

isFetchItemsNodeDefinition

isFieldsNodeDefinition

isFieldsNodeOrCollectionFieldsNode

  • isFieldsNodeOrCollectionFieldsNode(value: GraphNode): boolean

isFirstNodeDefinition

isFloorNodeDefinition

isFlowNodeDefinition

isFnNodeDefinition

isFormatNodeDefinition

isFromBase64NodeDefinition

isFromPromiseNodeDefinition

isFromStreamNodeDefinition

isFuzzyTraverseNodeDefinition

isGenerator

  • isGenerator<T>(input: any): boolean

isGetChildOperation

isGetChildRequest

isGetItemsOperation

isGetItemsRequest

isGetLengthNodeDefinition

isGetNodeDefinition

isGraphAction

  • isGraphAction(value: any): boolean

isGraphNode

  • isGraphNode(value: any): boolean

isGraphNodeNodeDefinition

isGraphOperation

  • isGraphOperation(value: any): boolean

isGtNodeDefinition

isGteNodeDefinition

isHasherFactory

isIdentityNodeDefinition

isIdentityOperation

isIfElseNodeDefinition

isIfErrorNodeDefinition

isIfPendingNodeDefinition

isIncludesNodeDefinition

isInclusiveSliceBounds

  • isInclusiveSliceBounds(value: any): boolean

isInitOperation

isInjectDependenciesNodeDefinition

isIntegerValueNode

  • isIntegerValueNode(node: GraphNode): boolean

isInvalidateNodeDefinition

isInvalidateOnNodeDefinition

isIsNilNodeDefinition

isIsPendingNodeDefinition

isIsPendingOperation

isIsUpdatingNodeDefinition

isIsUpdatingOperation

isItemPlaceholderNodeDefinition

isIterateOperation

isIteratorResultNodeDefinition

isJestAsymetricMatcher

  • isJestAsymetricMatcher(value: any): boolean

isJoinNodeDefinition

isKeyNodeDefinition

isLastNodeDefinition

isLegacyDataNode

isLegacyQueryNodeDefinition

isLengthNodeDefinition

isLengthOperation

isListKeyNode

isListKeyNodeDefinition

isLocationDataNodeDefinition

isLocationNodeDefinition

isLocationPathNodeDefinition

isLogNodeDefinition

isLowerCaseNodeDefinition

isLtNodeDefinition

isLteNodeDefinition

isMatchPatternNodeDefinition

isMatcher

  • isMatcher(value: any): boolean

isMatcherKey

  • isMatcherKey(name: string): boolean

isMaxNodeDefinition

isMinNodeDefinition

isModNodeDefinition

isMultiplyNodeDefinition

isNil

  • Creates an instance of an isNil node, which is a node used when checking if a given target is nil.

    example

    Check if target node is nil

    import muster, { isNil, nil, ref, value } from '@dws/muster';
    
    const app = muster({
      currentValue: value('some current value'),
      previousValue: nil(),
    });
    
    await app.resolve(isNil(ref('currentValue'))); // === false
    
    await app.resolve(isNil(ref('previousValue'))); // === true

    This example shows how to check if a given node is nil(or resolves to a nil).

    Parameters

    Returns IsNilNodeDefinition

isNilNodeDefinition

isNodeDefinition

  • isNodeDefinition(value: any): boolean

isNodeLikeCallArgumentArray

isNodeLikeCallArgumentMap

isNodeListNodeDefinition

isNodeType

  • isNodeType(value: any): boolean

isNotFoundNode

  • isNotFoundNode(value: any): boolean

isNotFoundNodeDefinition

  • isNotFoundNodeDefinition(value: any): boolean

isNotNodeDefinition

isNotPending

isNotPending

isNthNodeDefinition

isNumberValueNode

  • isNumberValueNode(node: GraphNode): boolean

isOkNodeDefinition

isOnGlobalEventDebouncedNodeDefinition

  • isOnGlobalEventDebouncedNodeDefinition(value: NodeDefinition): boolean

isOnGlobalEventNodeDefinition

isOnNodeDefinition

isOnStreamEmissionNodeDefinition

isOnceNodeDefinition

isOperationType

  • isOperationType(value: any): boolean

isOptimisticNodeDefinition

isOrNodeDefinition

isOtherwiseNodeDefinition

isParallelNodeDefinition

isParamContextId

  • isParamContextId(contextId: string | symbol): boolean

isParamNodeDefinition

isParentNodeDefinition

isParseFloatNodeDefinition

isParseIntNodeDefinition

isPartialNodeDefinition

isPending

isPendingNodeDefinition

isPendingOperation

isPlaceholderNodeDefinition

isPlainObject

  • isPlainObject(value: any): boolean

isPopOperation

isPositiveIntegerValueNode

  • isPositiveIntegerValueNode(node: GraphNode): boolean

isPowNodeDefinition

isPromise

  • isPromise<T>(object?: any | PromiseLike<T>): boolean

isPropertyNodeDefinition

isProxiedNode

  • isProxiedNode(value: any): boolean

isProxyNodeDefinition

isPushOperation

isQueriesSnapshotNotEmpty

isQueryNodeDefinition

isQuerySetCallOperationNodeDefinition

  • isQuerySetCallOperationNodeDefinition(value: NodeDefinition): boolean

isQuerySetCatchErrorNodeDefinition

isQuerySetChild

isQuerySetDeferNodeDefinition

isQuerySetGetChildOperationNodeDefinition

  • isQuerySetGetChildOperationNodeDefinition(value: NodeDefinition): boolean

isQuerySetGetItemsOperationNodeDefinition

  • isQuerySetGetItemsOperationNodeDefinition(value: NodeDefinition): boolean

isQuerySetIsPendingNodeDefinition

isQuerySetNodeDefinition

isQuerySetOperationNodeDefinition

isQuerySetResultNodeDefinition

isQuerySetSetOperationNodeDefinition

  • isQuerySetSetOperationNodeDefinition(value: NodeDefinition): boolean

isQuoteNodeDefinition

isRegexNodeDefinition

isRelativeSliceBounds

  • isRelativeSliceBounds(value: any): boolean

isRemoveItemAtOperation

isRemoveItemOperation

isRemoveItemsOperation

isReplaceNodeDefinition

isRequestOperation

isRequiredContextDependency

isResetNodeDefinition

isResetOperation

isResolveNodeDefinition

isResolveOperation

isResultOperation

isRootAndPath

  • isRootAndPath(value: any): boolean

isRootNodeDefinition

isRoundNodeDefinition

isSanitizable

  • isSanitizable(value: any): boolean

isSanitizable

  • isSanitizable(value: any): boolean

isScope

  • isScope(value: any): boolean

isScopeNodeDefinition

isSentenceCaseNodeDefinition

isSerializableQuerySetChild

isSerializedGraphOperation

  • isSerializedGraphOperation(value: any): boolean

isSerializedMusterType

  • isSerializedMusterType(value: any): boolean

isSerializedNode

  • isSerializedNode(value: any): boolean

isSeriesNodeDefinition

isSetNodeDefinition

isSetOperation

isSetResultNodeDefinition

isShiftOperation

isSplitNodeDefinition

isSqrtNodeDefinition

isStartCaseNodeDefinition

isStartsWithNodeDefinition

isStatefulNode

isStatefulNodeDefinition

isStatefulNodeType

  • isStatefulNodeType(nodeType: NodeType): boolean

isStatefulOperationHandlerDefinition

isStepOperation

isStream

  • isStream(value: any): boolean

isStringValueNode

  • isStringValueNode(node: GraphNode): boolean

isSubstringNodeDefinition

isSubtractNodeDefinition

isSwitchOnNodeDefinition

isTakeLastNodeDefinition

isTestNodeDefinition

isToBase64NodeDefinition

isToStringNodeDefinition

isTransformItemsOperation

isTransformer

isTraverseNodeDefinition

isTreeNodeDefinition

isTrimNodeDefinition

isTruncateNodeDefinition

isUnshiftOperation

isUpdateNodeDefinition

isUpdating

isUpdatingOperation

isUpperCaseNodeDefinition

isValidIteratorResult

  • isValidIteratorResult(node: GraphNode): boolean

isValidSortValue

  • isValidSortValue(value: GraphNode): boolean

isValueNodeDefinition

isValueNodeOrCallableNode

  • isValueNodeOrCallableNode(node: GraphNode): boolean

isVariableNodeDefinition

isWhenNodeDefinition

isWithContextNodeDefinition

isWithScopeNodeDefinition

isWithTransformsNodeDefinition

itemId

itemPlaceholder

itemWithId

iterate

iterateOperation

iteratorResult

join

  • Creates a new instance of a join node, which is used when joining a number of strings together. The node expects each operand to be a value containing a string value. The node works in a similar way to Array.join from JS.

    example

    Join strings

    import muster, { join } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(join(' ', 'Hello', 'world'));
    // === 'Hello world';
    example

    Join array of strings

    import muster, { join, ref, value } from '@dws/muster';
    
    const app = muster({
      names: value(['Bob', 'Jane', 'Kate']),
    });
    
    await app.resolve(join(' ', ref('names')));
    // === 'Bob Jane Kate'
    example

    Join a collection of strings

    import muster, { entries, join, joinItems, query, ref } from '@dws/muster';
    
    const app = muster({
      names: ['Bob', 'Jane', 'Kate'],
    });
    
    await app.resolve(join(' ', query(ref('names'), entries())));
    // === 'Bob Jane Kate'
    
    // OR
    
    await app.resolve(joinItems(' ', ref('names')));
    // === 'Bob Jane Kate'

    Parameters

    Returns JoinNodeDefinition

joinItems

  • A helper function that creates a join node with each operand mapped to a query(operand, entries()). See the join documentation page to find out more.

    example

    Join a collection of strings

    import muster, { entries, join, joinItems, query, ref } from '@dws/muster';
    
    const app = muster({
      names: ['Bob', 'Jane', 'Kate'],
    });
    
    await app.resolve(joinItems(' ', ref('names')));
    // === 'Bob Jane Kate'

    Parameters

    Returns JoinNodeDefinition

just

  • just<T>(value: T): Stream<T>

key

last

  • Creates a new instance of the last node, which can be used as part of a ref to request a last item of a given collection.

    example

    Get last primitive item from a collection

    import muster, { last, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3],
    });
    
    await app.resolve(ref('numbers', last())); // === 3

    This example shows how to get the last item from the collection, when the collection contains only primitive items.

    example

    Query the last item from a collection

    import muster, { key, last, query, ref } from '@dws/muster';
    
    const app = muster({
      people: [
        { firstName: 'Bob', lastName: 'Smith' },
        { firstName: 'Jane', lastName: 'Jonson' },
        { firstName: 'Sabine', lastName: 'Summers' },
      ],
    });
    
    await app.resolve(query(ref('people', last()), {
      firstName: key('firstName'),
      lastName: key('lastName'),
    })); // === { firstName: 'Sabine', lastName: 'Summers' }

    This example shows how to get the last item from the collection, when the collection contains tree nodes.

    Returns LastNodeDefinition

lastItem

  • Creates a new instance of a lastItem node, which is a type of collection transform used when taking the last item out of a collection. It also comes with a shorthand version to be used in the ref. See the References to items in collections example from the ref documentation.

    example

    Take last item (using transform)

    import muster, { entries, query, ref, lastItem, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const item = await app.resolve(query(ref('numbers'), withTransforms([
      lastItem(),
    ], entries())));
    // item === [5]

    This example shows how to use the lastItem transform to take the last item out of a collection.

    Returns LastItemNodeDefinition

leftPad

  • leftPad(minLength: number, value: string): string

legacyQuery

  • Creates an instance of a legacyQuery node, which is a node used to request values from multiple NodeDefinitions at a time. This node is used internally by Muster-React when creating bindings between components and the graph. See Muster-React for more information.

    By default, the legacyQuery waits for every field to resolve to a non-dynamic node. This behaviour can be modified through the use of the isPending and the defer.

    A legacyQuery resolves into a tree, an array or a value (depending on the type of the legacyQuery made). These can be easily converted into plain JS objects with the valueOf helper. This conversion is reversible through the use of toNode helper.

    example

    Basic legacyQuery

    import muster, { key, legacyQuery, root, valueOf } from '@dws/muster';
    
    const app = muster({
      firstName: 'Rosalind',
      lastName: 'Franklin',
      dateOfBirth: 1948,
    });
    
    const user = await app.resolve(legacyQuery(root(), {
      userFirstName: key('firstName'),
      lastName: key('lastName'),
    }));
    // user = {
    //   userFirstName: 'Rosalind',
    //   lastName: 'Franklin',
    // }

    This example shows how to use a legacyQuery to request two NodeDefinition at the same time. The legacyQuery call consists of: the first argument which defines the graph starting point from which legacyQuery should begin the traversal; and the second argument, an object (implicitly cast to a fields) which defines a map of fields to retrieve from the graph. The name of each property in that map corresponds to the name in the output tree. Note that this name does not have to be the same as the name in the key on the right of that property. Take the firstName graph node and its corresponding userFirstName name in the legacyQuery. The ability to override the name of a node is useful especially when a given NodeDefinition can be accessed in more than one way. This behaviour is used extensively by the proxy, and by extension the remote, when building a legacyQuery to a remote node.

    The key used in this legacyQuery defines the name of a given node in the graph. Additionally, the key can define a map of child nodes to retrieve from that node. See the "Getting values of nested nodes" example for more information.

    A legacyQuery resolves into a combination of trees, arrays and values. This means an output of one legacyQuery can be used as an input for another NodeDefinition and even another legacyQuery.

    example

    Getting async values

    import muster, { fromPromise, key, legacyQuery, root } from '@dws/muster';
    
    let resolvePromise1;
    const app = muster({
      name: 'sync name',
      asyncName: fromPromise(() =>
        new Promise((res) => resolvePromise1 = res)
          .then(() => 'async name'),
      ),
    });
    
    console.log('Making the legacyQuery');
    app.resolve(legacyQuery(root(), {
      name: key('name'),
      asyncName: key('asyncName'),
    })).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Resolving the promise');
    resolvePromise1();
    
    // Console output:
    // Making the legacyQuery
    // Resolving the promise
    // {
    //   name: 'sync name',
    //   asyncName: 'async name',
    // }

    The legacyQuery by default waits for every part of the legacyQuery to resolve to a non-pending and non-dynamic value. This example demonstrates this behaviour with the help of fromPromise. Note that the legacyQuery output gets logged only once - after the promise is resolved. Muster can also mark certain parts of the legacyQuery with defers. This instructs Muster to return the legacyQuery result even if that part of the legacyQuery is loading. See the "Defer part of the legacyQuery" example for more information.

    example

    Getting values of nested nodes

    import muster, { key, legacyQuery, root } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'Rosalind',
        lastName: 'Franklin',
      },
    });
    
    const user = await app.resolve(legacyQuery(root(), {
      user: key('user', {
        firstName: key('firstName'),
      }),
    }));
    // user = {
    //   user: {
    //     firstName: 'Rosalind',
    //   },
    // }

    The legacyQuery can extract values from nested NodeDefinitions. As shown in the previous example, the legacyQuery factory function performs an implicit conversion to a fields. This saves developers from having to explicitly write unnecessarily verbose code. The same functionality is available in the key. When the factory is called with a pure JS object, it will recursively cast it to a fields.

    Sometimes, the second argument to the key won't be a pure JS object. For example, when a developer wants to get items from a collection. fields lets the legacyQuery know that a target NodeDefinition is expected to be a container-like node. This assumption breaks apart when requesting a collection. To request items from collections, one has to make a legacyQuery with an entries instead of a fields. See the "Getting atomic items from a collection" example to find out more.

    example

    Getting atomic items from a collection

    import muster, { entries, key, legacyQuery, root } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
    });
    
    const numbers = await app.resolve(legacyQuery(root(), {
      numbers: key('numbers', entries()),
    }));
    // numbers = {
    //   numbers: [1, 2, 3, 4],
    // }

    An entries can be provided instead of a fields to instruct the legacyQuery to retrieve all items from a given graph node. In this example, we had it easy: every item is an atomic value. The fun with legacyQuerys and collections does not end here. See the "Getting specific fields from items" example to learn more about selecting certain fields from items.

    example

    Getting specific fields from items

    import muster, { entries, key, legacyQuery, ref } from '@dws/muster';
    
    const app = muster({
      books: [
        { name: 'The Expeditionary Force', author: 'Craig Alanson' },
        { name: 'Fear The Sky', author: 'Stephen Moss' },
        { name: 'After It Happened', author: 'Devon Ford' },
      ],
    });
    
    const bookNames = await app.resolve(legacyQuery(ref('books'), entries({
      name: key('name'),
    })));
    // bookNames = [
    //   { name: 'The Expeditionary Force' },
    //   { name: 'Fear The Sky' },
    //   { name: 'After It Happened' },
    // ]

    In this example, apart from getting just a selected field from each item in the collection, we demonstrated another feature of the legacyQuery: changing its starting point. In all previous examples, we've used a root as the starting point of the legacyQuery, but this time to make the output shorter we've changed it to a books collection.

    example

    Creating setters

    import muster, {
      createSetter,
      key,
      legacyQuery,
      root,
      variable,
    } from '@dws/muster';
    
    const app = muster({
      name: variable('initial'),
    });
    
    console.log('Making a legacyQuery for `name`');
    app.resolve(legacyQuery(root(), { name: key('name') })).subscribe((result) => {
      console.log(result);
    });
    
    console.log('Making a legacyQuery for setter function');
    const result = await app.resolve(legacyQuery(root(), {
      setName: createSetter('name'),
    }));
    
    console.log('Calling a setter');
    result.setName('updated');
    
    // Console output:
    // Making a legacyQuery for `name`
    // initial
    // Making a legacyQuery for setter function
    // Calling a setter
    // updated

    This example shows how a legacyQuery can be used when there's a need for imperative call to a set method. This setter function can be used, for example, when integrating with view frameworks such as React, Vue etc. Muster-React uses this way of creating setters extensively. Similarly, there's a createCaller node which allows for imperative calls to actions.

    createSetters and createCallers should be used only when the output of the legacyQuery is used outside the "Muster world". Inside Muster code, using calls applys and sets is recommended for these kinds of actions.

    example

    Defer part of a legacyQuery

    import muster, { defer, fromPromise, key, legacyQuery, root } from '@dws/muster';
    
    let resolvePromise2;
    const app = muster({
      name: 'sync name',
      asyncName: fromPromise(() =>
        new Promise((res) => resolvePromise2 = res)
          .then(() => 'async name'),
      ),
    });
    
    console.log('Requesting the legacyQuery');
    app.resolve(legacyQuery(root(), {
      name: key('name'),
      asyncName: defer('asyncName'),
    })).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Resolving the promise');
    resolvePromise2();
    
    // Console output:
    // Requesting the legacyQuery
    // {
    //   name: 'sync name',
    //   asyncName: null,
    // }
    // Resolving the promise
    // {
    //   name: 'sync name',
    //   asyncName: 'async name',
    // }

    This example demonstrates how to instruct a legacyQuery to return the output of its legacyQuery even if a given NodeDefinition is in a pending state. The legacyQuery is built with a defer. This example uses a shorthand syntax for the defer(...) node. Internally, the node converts the argument to a key:

    import { defer, key } from '@dws/muster';
    
    defer('asyncName');
    // is equivalent to
    defer(key('name'));

    The defer also enables the defer part of the legacyQuery to return a previously loaded (stale) value of the target node. See the "Defer with previous value" example for more information.

    example

    Check if defer part of the legacyQuery is loading

    import muster, {
      defer,
      fromPromise,
      isPending,
      key,
      legacyQuery,
      root,
    } from '@dws/muster';
    
    let resolvePromise3;
    const app = muster({
      name: 'sync name',
      asyncName: fromPromise(() =>
        new Promise((res) => resolvePromise3 = res)
          .then(() => 'async name'),
      ),
    });
    
    console.log('Requesting the legacyQuery');
    app.resolve(legacyQuery(root(), {
      name: key('name'),
      asyncName: defer('asyncName'),
      isLoadingAsyncName: isPending('asyncName'),
    })).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Resolving the promise');
    resolvePromise3();
    
    // Console output:
    // Requesting the legacyQuery
    // {
    //   name: 'sync name',
    //   asyncName: null,
    //   isLoadingAsyncName: true,
    // }
    // Resolving the promise
    // {
    //   name: 'sync name',
    //   asyncName: 'async name',
    //   isLoadingAsyncName: false,
    // }

    This example presents the use of the isPending. When used in a legacyQuery, this node checks if a part of the legacyQuery is currently loading. Similarly to the defer, the isPending factory function implicitly converts its argument to a key.

    import { isPending, key } from '@dws/muster';
    
    isPending('asyncName');
    // is equivalent to
    isPending(key('asyncName'))

    Parameters

    Returns LegacyQueryNodeDefinition

length

  • Creates a new instance of the length node. This node can be used as part of a ref node to get a length of a collection, or as a standalone node which computes a length of a target collection

    example

    Get a length of a collection as part of a ref

    import muster, { length, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3],
    });
    
    await app.resolve(ref('numbers', length())); // === 3

    This example shows how to use length node as part of a ref to get a length of a collection.

    example

    Get a length of a target collection

    import muster, { length, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3],
    });
    
    await app.resolve(length(ref('numbers'))); // === 3

    This example shows how to get a length of a target collection by specifying a target of the length() node.

    Returns LengthNodeDefinition

  • Parameters

    Returns GetLengthNodeDefinition

lengthOperation

location

  • Creates a new instance of a location node, which is a type of a NodeDefinition used when accessing browser location. This node allows for reading/writing to the address bar, and can be used to implement custom routing mechanism. The path can be encoded using following formats:

    • slash: #/home
    • noslash: #home
    • hashbang: #!/home

    Additionally, the node allows storing parameters both as URL encoded values, and as JSON serialized objects.

    example

    Get current location

    import muster, { location, ref } from '@dws/muster';
    
    const app = muster({
      navigation: location(),
    });
    
    // Given a URL: #/
    await app.resolve(ref('navigation'));
    // === { path: '/', params: {} }
    
    // Given a URL: #/home?showWelcome=true
    await app.resolve(ref('navigation'));
    // === { path: '/home', params: { showWelcome: 'true' } }

    This example shows how to get current path with parameters as a combined object.

    example

    Set current location

    import muster, { location, ref, set } from '@dws/muster';
    
    const app = muster({
      navigation: location(),
    });
    
    // Given a URL: #/home
    await app.resolve(set(ref('navigation'), { path: '/user', params: { id: 10 } }));
    // URL after set: #/user?id=10

    This example shows how to set the current location to a new value.

    example

    Get current path

    import muster, { location, ref } from '@dws/muster';
    
    const app = muster({
      navigation: location(),
    });
    
    // Given a URL: #/home?test=value
    await app.resolve(ref('navigation', 'path'));
    // === '/home'

    This example shows how to get only the path part of the URL. Internally the 'path' is handled by the locationPath node.

    example

    Set current path

    import muster, { location, ref, set } from '@dws/muster';
    
    const app = muster({
      navigation: location(),
    });
    
    // Given a URL: #/home?id=12
    await app.resolve(set(ref('navigation', 'path'), '/user'));
    // URL after set: #/user?id=12

    This example shows how to set only the path without overwriting path params. Internally the 'params' is handled by the locationPath node.

    example

    Get current params

    import muster, { location, ref } from '@dws/muster';
    
    const app = muster({
      navigation: location(),
    });
    
    // Given a URL: #/home?id=12
    await app.resolve(ref('navigation', 'params'));
    // === { id: '12' }

    This example shows how to get the current path parameters. Internally the 'params' is handled by the locationData node.

    example

    Set current params

    import muster, { location, ref, set } from '@dws/muster';
    
    const app = muster({
      navigation: location(),
    });
    
    // Given a URL: #/home?id=12
    await app.resolve(set(ref('navigation', 'params'), { test: 'value' }));
    // URL after set: #/home?test=value

    This example shows how to set the path parameters without overwriting the path. Internally the 'params' is handled by the locationData node.

    Parameters

    Returns NodeDefinition

locationData

locationPath

  • locationPath(history: History, update?: undefined | false | true): NodeDefinition

locationToLocationValue

log

  • Creates a new instance of a log node, which is a type of a NodeDefinition used for logging a value of a target node every time it emits a new value.

    example

    Log computed value

    import muster, { computed, log, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      balance: variable(500),
      bet: variable(100),
      canBet: log(
        computed(
          [ref('balance'), ref('bet')],
          (balance, bet) => balance >= bet,
        ),
      ),
    });
    
    // Just subscribe, no need to log anything as LogNode will handle that
    app.resolve(ref('canBet')).subscribe((canBet) => {});
    
    await app.resolve(set('bet', 510));
    
    await app.resolve(set('bet', 30));
    
    // Console output:
    // { input: <<computed node>>, output: value(true) }
    // { input: <<computed node>>, output: value(false) }
    // { input: <<computed node>>, output: value(true) }

    Parameters

    Returns LogNodeDefinition

logMiddleware

lowerCase

  • Creates a new instance of a lowerCase node, which is used when converting a string to a lower case string. The node expects the subject to be a value that contains a string value. It works in a similar way to the String.toLowerCase method in JavaScript.

    example

    Convert string to lower case

    import muster, { lowerCase } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(lowerCase('Hello World'));
    // === 'hello world'

    Parameters

    Returns LowerCaseNodeDefinition

lt

  • Creates a new instance of a lt node, which is used to check if a given node's value is less than the value of another graph node. This comparison is done with the < operator.

    example

    Comparing values

    import muster, { computed, lt } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(lt(5, 4)) // === false
    await app.resolve(lt(5, 5)) // === false
    await app.resolve(lt(5, 6)) // === true
    await app.resolve(lt(computed([], () => 100), 99)) // === false
    await app.resolve(lt(computed([], () => 100), 100)) // === false
    await app.resolve(lt(computed([], () => 100), 101)) // === true

    Parameters

    Returns LtNodeDefinition

lte

  • Creates a new instance of a lte node, which is used to check if a given node's value is less than or equal to the value of another graph node. This comparison is done with the <= operator.

    example

    Comparing values

    import muster, { computed, lte } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(lte(5, 4)) // === false
    await app.resolve(lte(5, 5)) // === true
    await app.resolve(lte(5, 6)) // === true
    await app.resolve(lte(computed([], () => 100), 99)) // === false
    await app.resolve(lte(computed([], () => 100), 100)) // === true
    await app.resolve(lte(computed([], () => 100), 101)) // === true

    Parameters

    Returns LteNodeDefinition

map

  • Creates a new instance of a map node, which is a type of collection transform used when mapping items from one representation from to another. This type of transform can be thought of as akin to JavaScript's Array.map function.

    example

    Simple mapper

    import muster, { applyTransforms, entries, map, multiply, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
      numbersTimes2: applyTransforms(ref('numbers'), [
        map((item) => multiply(item, 2)),
      ]),
    });
    
    const numbersTimes2 = await app.resolve(query(ref('numbersTimes2'), entries()));
    // numbersTimes2 === [2, 4, 6, 8]

    This example shows how to use a map to multiply every item of the collection by 2. The multiplication is done with help of an arithmetic graph node, multiply.

    example

    Mapping branches

    import muster, { applyTransforms, get, entries, key, map, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
      numbersAsBranches: applyTransforms(ref('numbers'), [
        map((item) => ({ number: item })),
      ]),
    });
    
    const numbers = await app.resolve(query(ref('numbersAsBranches'), entries({
      number: key('number'),
    })));
    // numbers === [
    //   { number: 1 },
    //   { number: 2 },
    //   { number: 3 },
    //   { number: 4 },
    // ]

    This example shows how to use a map transform to change the shape of items. It converts each item from a simple value to a tree with a branch named number containing the item's original value.

    Parameters

    Returns MapNodeDefinition

  • Parameters

    Returns MapNodeDefinition

map

  • map<T, V>(project: function, stream: Stream<T>): Stream<V>

mapQ

  • mapQ<T, R>(iteratee: function, queue: Queue<T>): Array<R>

mapRecursive

  • mapRecursive<T>(project: function, stream: Stream<T>): Stream<T>

mapValues

  • mapValues(object: any, iteratee: function): any

match

  • match(predicate: KeyMatcher, param?: undefined | string): string

matchPattern

  • Creates a new instance of a matchPattern node, which is used finding all regex matches from a given string. The node expects the subject to be a value that contains a string value and a regex which is a regex. It works in a similar way to the String.match node. The node resolves to an array.

    example

    Getting matches

    import muster, { matchPattern, regex } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(matchPattern(regex(/\d+/g), '123 321'));
    // === [
    //   '123',
    //   '321',
    // ]

    Parameters

    Returns MatchPatternNodeDefinition

max

  • Creates a new instance of a max node, which is a type of a NodeDefinition used when retrieving a maximum value of given operands. The node expects the operands to be a value node that contains a numeric value. It work in a similar way as the Math.max(...) function from JS.

    example

    Compute the maximum value

    import muster, { max, ref } from '@dws/muster';
    
    const app = muster({
      zero: 0,
    });
    
    await app.resolve(max(1, ref('zero'), 0.5));
    // === '1'

    Parameters

    Returns MaxNodeDefinition

merge

mergeHashSets

  • mergeHashSets(set1: Set<string>, set2: Set<string>): Set<string>

min

  • Creates a new instance of a min node, which is a type of a NodeDefinition used when retrieving a minimum value of given operands. The node expects the operands to be a value node that contains a numeric value. It work in a similar way as the Math.min(...) function from JS.

    example

    Compute the minimum value

    import muster, { min, ref } from '@dws/muster';
    
    const app = muster({
      zero: 0,
    });
    
    await app.resolve(min(1, ref('zero'), 0.5));
    // === '0.5'

    Parameters

    Returns MinNodeDefinition

mockFn

mockResponseMiddleware

mod

  • Creates a new instance of a mod node, which is a type of NodeDefinition used to perform a modulo operation on number-based values. The mod node takes any number of operands. It will throw an error if the number of operands is below 2 as it doesn't make sense to do the modulo operation with a single operand.

    example

    Modulo 5

    import muster, { mod, ref } from '@dws/muster';
    
    const app = muster({
      fourteen: 14,
      five: 5,
    });
    
    const result = await app.resolve(
      mod(ref('fourteen'), ref('five')),
    );
    // result === 4

    This example shows how to do the modulo operation with the use of mod.

    Parameters

    Returns ModNodeDefinition

multiply

  • Creates a new instance of a multiply node, which is a type of NodeDefinition used to multiply number-based values. The multiply takes any number of operands. It will throw an error if the number of operands is below 2 as it doesn't make sense to do the multiplication with a single operand.

    example

    Multiply by two

    import muster, { multiply, ref } from '@dws/muster';
    
    const app = muster({
      five: 5,
      two: 2,
    });
    
    const result = await app.resolve(
      multiply(ref('five'), ref('two')),
    );
    // result === 10

    This example shows how to multiply with the use of the multiply.

    example

    Multiply five numbers

    import muster, { add, computed, multiply, ref, variable } from '@dws/muster';
    
    const app = muster({
      five: 5,
      four: computed([], () => 4),
      three: variable(3),
      two: add(ref('one'), ref('one')),
      one: 1,
    });
    
    const result = await app.resolve(
      multiply(ref('five'), ref('four'), ref('three'), ref('two'), ref('one')),
    );
    // result === 120

    This example shows how to multiply five differently computed numbers. As mentioned in the description above, this node can handle any number of operands as long as they resolve to a numeric value node.

    Parameters

    Returns MultiplyNodeDefinition

muster

  • Creates a new muster instance based on the graph definition parameter.

    See Muster class for more details on the methods available in the returned application object.

    graph definition object can be defined using plain javascript objects. These objects are converted to graph nodes. The conversion follows these rules:

    • Any NodeDefinition, e.g. value, computed etc. remains unchanged.
    • A simple value e.g. string, number, Date, etc. is converted to a value.
    • A plain object e.g. { firstName: 'Bob', lastName: 'Builder' } is converted to a tree. Each property of that branch is recursively converted using these rules.
    • An array of simple values e.g. [1, 2, 3] is converted to an array with each item being converted to a value.
    • An array of plain objects e.g. [{ name: 'first' }, { name: 'second' }] is converted to an array with each item being converted to a tree. Each property of that branch is recursively converted using these rules. You can find more about default conversions in the graph helper documentation.

    Important notice: Values of the graph nodes are evaluated only when a subscription for a node is made. Subscriptions can be created in two ways:

    • Explicitly - by calling app.resolve(nodeToSubscribe), where nodeToSubscribe is a NodeDefinition to subscribe to
    • Implicitly - by returning a dynamic node from NodeType operation implementation.

    See "Lazy-evaluating values" example for a code example.

    example

    Creating basic muster application

    import muster from '@dws/muster';
    
    const app = muster({
      firstName: 'John',
      lastName: 'Doe',
      age: 43,
    });

    This example creates a muster application containing three nodes:

    example

    Accessing data from a muster graph

    import muster from '@dws/muster';
    
    const app = muster({ firstName: 'John' });

    First let's create a simple muster instance with a graph containing a single leaf value firstName. Now we have an instance of muster we can make queries against it:

    import muster, { ref } from '@dws/muster';
    
    const app = muster({ firstName: 'John' });
    
    const firstName = await app.resolve(ref('firstName'));

    The Muster object exposes a resolve method which can be used for running queries against muster. In this example we've used a ref. This helper is used to locate and return a graph node based on its path in the graph. The path in the graph is defined by the hierarchy of branches that exist in the muster graph. In this example we have just one branch containing a single leaf firstName. You can find out more about paths and branches in the ref and tree documentation.

    app.resolve returns an object implementing both Observable and Promise APIs. In this example we have retrieved the current value of the firstName node with the use of the Promise API. Alternatively this can also be done with Observable by subscribing to the returned observable:

    import muster, { ref } from '@dws/muster';
    
    const app = muster({ firstName: 'John' });
    
    const unsubscribe = app.resolve(ref('firstName')).subscribe((firstName) => {
      // Do something with the first name as it changes over time
    });

    By nature, muster tries to execute the code synchronously when it can, so the callback of the subscribe will be called immediately with the latest value of firstName. In this example firstName resolves to a 'John' string.

    Notice: subscribe has one important advantage over await. It responds to changes in the subscribed query over time. Consider an example where the firstName is a node whose value changes while the application is running. Promise will emit the value as soon as it's available but won't cause your code to be re-run when the value of the subscribed node changes. On the other hand, Observable will re-emit a new value causing the subscriber (the function used to create the subscription) to be executed again with a new value.

    See variable, fromPromise and fromStream for more information about settable nodes.

    example

    Creating muster application with branches

    import muster, { computed, ref } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'John',
        lastName: 'Doe',
        fullName: computed([
          ref('user', 'firstName'),
          ref('user', 'lastName'),
        ], (firstName, lastName) => `${firstName} ${lastName}`),
      },
    });

    This example creates a muster application where the graph has one branch user (tree). That branch has three leaves:

    • firstName: value = 'John'
    • lastname: value = 'Doe'
    • fullName: computed = A node which computes full name of the user based on the current value of firstName and lastName.

    Note the fullName computed dependencies are defined using fully qualified path of the nodes in the graph. This could have been simplified with the use of a relative helper function:

    import muster, { computed, ref, relative } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'John',
        lastName: 'Doe',
        fullName: computed([
          ref(relative('firstName')),
          ref(relative('lastName')),
        ], (firstName, lastName) => `${firstName} ${lastName}`),
      },
    });

    The benefit of using relative instead of defining the full path is apparent when refactoring the application graph. Imagine a scenario when the user branch is to be renamed to currentUser. In this scenario, when the full path is used we'd have to change the name in three places: branch definitions and both references. It would be much simpler with the use of relative helper: we'd have to only rename the branch.

    You can find out more about relative helper on its documentation.

    example

    Lazy-evaluating values

    import muster, { computed, ref } from '@dws/muster';
    
    let externalValue = 'initial';
    
    const app = muster({
      testComputed: computed([], () => {
        externalValue = 'updated';
        return true;
      }),
    });
    
    // externalValue === 'initial'
    
    const subscription = app.resolve(ref('testComputed'));
    
    // externalValue === 'initial'
    
    const unsubscribe = subscription.subscribe((testComputedValue) => {
      // externalValue === 'updated'
      // testComputedValue === true
    });
    
    // externalValue === 'updated'

    This example demonstrates the principle of lazy evaluation in muster. In muster the value of every node is evaluated only when a subscription is created to that node. Note how the value of externalValue changes in this example. Thanks to the synchronous code execution in muster the externalValue is set to the new value before the first line of the subscriber callback as well as after the call to the subscribe method.

    Most of the Muster NodeDefinitions are synchronous, with exception of fromPromise, fromStream (depending on the type of stream used), action, proxy and remote.

    example

    Complex queries

    import muster, { key, query, root } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'Bob',
        lastName: 'Johnson',
      },
    });
    
    const userTree = await app.resolve(query(root(), {
      user: key('user', {
        firstName: key('firstName'),
        lastName: key('lastName'),
      }),
    }));
    // userTree is a JS object with all of the requested branches encoded in it:
    // {
    //   user: {
    //     firstName: 'Bob',
    //     lastName: 'Johnson',
    //   },
    // }

    In previous examples we've been requesting a single NodeDefinition at a time. In real world apps this would not be the most efficient or fastest way of writing code. For this reason Muster comes with a query which allows for building complex queries. These queries define the shape of their output data as well as the place from the graph this data is to be retrieved from. See the query documentation to learn more about queries.

    Parameters

    • root: NodeLike
    • Optional options: undefined | object

    Returns Muster

    Configured instance of the muster app.

never

nil

  • nil(value: null): string

nil

nodeList

normalizePath

not

  • Creates a new instance of a not node, which is used when negating the value of a graph node. This node expects the expression to resolve to a value. It throws an error if an expression resolves to any other type.

    example

    Negating values

    import muster, { computed, not, value } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(not(false)) // === true
    await app.resolve(not(true)) // === false
    await app.resolve(not('hello world')) // === false
    await app.resolve(not(123)) // === false
    await app.resolve(not(value({ }))) // === false
    await app.resolve(not(not(true))) // === true
    await app.resolve(not(computed([], () => false))) // === true
    await app.resolve(not(computed([], () => true))) // === false

    Parameters

    Returns NotNodeDefinition

notFound

nth

  • Creates a new instance of the nth node, which can be used as part of a ref to request a specific item of a given collection.

    example

    Get the second primitive item from a collection

    import muster, { nth, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3],
    });
    
    await app.resolve(ref('numbers', nth(1))); // === 2

    This example shows how to get the second item from the collection, when the collection contains only primitive items.

    example

    Query the second item from a collection

    import muster, { key, nth, query, ref } from '@dws/muster';
    
    const app = muster({
      people: [
        { firstName: 'Bob', lastName: 'Smith' },
        { firstName: 'Jane', lastName: 'Jonson' },
        { firstName: 'Sabine', lastName: 'Summers' },
      ],
    });
    
    await app.resolve(query(ref('people', nth(1)), {
      firstName: key('firstName'),
      lastName: key('lastName'),
    })); // === { firstName: 'Jane', lastName: 'Jonson' }

    This example shows how to get the second item from the collection, when the collection contains tree nodes.

    Parameters

    • index: number

    Returns NthNodeDefinition

nthItem

  • Creates a new instance of a nthItem node, which is a type of collection transform used to take a specific item out of a collection. The items are zero-index based so in order to take the first item you have to call nthItem(0), second item is nthItem(1) and so on. As with most nodes, a value will be implicitly mapped to a value node if it isn't a NodeDefinition already. This means the index can be a reference to another node in the graph. It also comes with a shorthand version to be used in the ref. See the References to items in collections example from the ref documentation.

    example

    Take third item (using transform)

    import muster, { entries, query, ref, nthItem, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const thirdItem = await app.resolve(query(ref('numbers'), withTransforms([
      nthItem(2),
    ], entries())));
    // thirdItem === [3]

    This example shows how to use a nthItem transform to take the third item out of a collection.

    Parameters

    Returns NthItemNodeDefinition

number

  • number(value: number): string

objectOf

objectToTree

ok

on

  • Creates a new instance of an on node, which is a type of NodeDefinition which can react to the dispatched Muster events. The node starts its lifecycle by emitting the initialValue. This value can then be changed by the callback when a correct event has arrived. See the dispatch documentation to learn more about dispatching events.

    example

    Change the value on event

    import muster, { dispatch, on, ref, value } from '@dws/muster';
    
    const app = muster({
      isOnline: on((event) => {
        if (event.type === 'online') return value(true);
        if (event.type === 'offline') return value(false);
        return undefined;
      }, true),
    });
    
    app.resolve(ref('isOnline')).subscribe((isOnline) => {
      console.log(isOnline ? 'Online' : 'Offline');
    });
    
    console.log('Dispatching `offline` event');
    await app.resolve(dispatch('offline'));
    
    // Console output:
    // Online
    // Dispatching `offline` event
    // Offline

    Parameters

    Returns OnNodeDefinition

onGlobalEvent

onGlobalEventDebounced

  • onGlobalEventDebounced(eventType: string | symbol, delay?: number): SchedulerFactory

onInvalidateNodeAction

onStreamEmission

onSubscribeNode

onSubscribeNodeAction

onSubscribeScope

  • onSubscribeScope(scope: Scope): void

onUnsubscribeNode

onUnsubscribeNodeAction

onUnsubscribeScope

  • onUnsubscribeScope(scope: Scope): void

onUpdateNodeAction

once

  • once(fn: function): function

once

  • Creates a new instance of a once, which is a type of a GraphNode that causes a given operation to be performed only once. Used by the call node to prevent action from re-triggering every time a dependency is changed.

    example

    Compute the value only once

    import muster, { computed, once, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
      greeting: computed([once(ref('name'))], (name) => `Hello, ${name}`),
    });
    
    app.resolve(ref('greeting')).subscribe((greeting) => {
      console.log(greeting);
    });
    
    console.log('Changing name to Jane');
    await app.resolve(set('name', 'Jane'));
    
    // Console output:
    // Hello, Bob
    // Changing name to Jane

    This example shows how to use the once to ensure the value of a computed gets computed only once and doesn't change when the name changes.

    Parameters

    Returns OnceNodeDefinition

oneOf

  • oneOf<T, P>(values: P): Matcher<T, P>

oneOfType

optimistic

  • Creates a new instance of the optimistic node. This node can be used to make an asynchronously settable node behave in a synchronous way by pretending that the set operation was synchronous, and by serving that value as a result of evaluate operation.

    example

    Wrap fromPromise in optimistic

    import muster, { fromPromise, ok, optimistic, ref, set, value } from '@dws/muster';
    
    const app = muster({
      userPreferences: optimistic(fromPromise({
        get: () => fetch('http://api.yourproject.com/user/preferences').then((result) => {
          console.log('Data loaded from the server');
          return result;
        }),
        set: (params, value) => fetch('http://api.yourproject.com/user/preferences', {
          body: JSON.stringify(value),
          method: 'POST',
        }).then((result) => {
          console.log('Data saved on the server');
          return ok();
        }),
      })),
    });
    
    console.log('Subscribing to userPreferences');
    let isFirstTime = true;
    app.resolve(ref('userPreferences')).subscribe((preferences) => {
      console.log('User preferences:', preferences);
      if (!isFirstTime) return;
      isFirstTime = false;
      console.log('Changing user preferences');
      app.resolve(set('userPreferences', value({ likeMuster: true }))).then(() => {});
    });
    
    // Console output:
    // Subscribing to userPreferences
    // Data loaded from the server
    // User preferences: { likeMuster: false }
    // Changing user preferences
    // User preferences: { likeMuster: true }
    // Data saved on the server

    Note that the userPreferences emitted before the set was completed. This is because the optimistic node assumes that the set operation will be successful, and immediately updates the evaluate operation output.

    Parameters

    Returns OptimisticNodeDefinition

optional

or

  • Creates a new instance of a or node, which introduces an or expression. It checks if at least one of its operands resolves to truthy. The conversion to boolean is done with the Boolean JS function. It requires every operand to resolve to a value. It throws an error if an operand resolves to any other node type.

    example

    Different variants of or operands

    import muster, { computed, or, value } from '@dws/muster';
    
    const app = muster({});
    await app.resolve(or(true)) // === true
    await app.resolve(or(false)) // === false
    await app.resolve(or(value(true))) // === true - it is equivalent to or(true)
    await app.resolve(or('hello world')) // === true
    await app.resolve(or(true, false)) // === true
    await app.resolve(or(false, false)) // === false
    await app.resolve(or(computed([], () => false))) // === false
    await app.resolve(or(computed([], () => true))) // === true
    await app.resolve(or(computed([], () => true), true)) // === true
    await app.resolve(or(computed([], () => true), false)) // === true
    await app.resolve(or(computed([], () => false), false)) // === false

    Parameters

    Returns OrNodeDefinition

otherwise

parallel

  • Creates a new instance of a parallel node, which is used to perform a set of operations as a single combined operation. The set of results is assembled into an array, maintaining the order of nodes provided to the parallel.

    Each input node is resolved to its result and then unsubscribed immediately. This means that, unlike the the combineLatest, the parallel resolves to a single combined result and will not update if the value of one of the input nodes is updated.

    example

    Performing multiple updates at the same time

    import muster, { parallel, set, variable } from '@dws/muster';
    
    const app = muster({
      firstName: variable('Bob'),
      lastName: variable('Jones'),
      age: variable(39),
    });
    
    await app.resolve(parallel([
      set('firstName', 'Jane'),
      set('lastName', 'Doe'),
      set('age', 24),
    ]));
    // === ['Jane', 'Doe', 24]

    This example shows how to use the parallel to set three variables at the same time.

    Parameters

    Returns ParallelNodeDefinition

param

  • Creates instance of the param node, which is used for accessing the value of a parameter from the current scope. Parameters are usually defined by a tree and match helper. See the tree documentation for more information.

    example

    Accessing parameter values

    import muster, { match, param, ref, types } from '@dws/muster';
    
    const app = muster({
      user: {
        [match(types.string, 'userId')]: param('userId'),
      },
      invalidParam: param('userId'),
    });
    
    const userId = await app.resolve(ref('user', '123-456'));
    // userId === '123-456'
    
    const invalid = await app.resolve(ref('invalidParam'));
    // invalid === 'Invalid parameter: "userId"'

    This example demonstrates how to access a named parameter from the current path. Usually the param resolves to a value with the value of a given parameter. See the tree for more information on matchers and branches.

    Parameters

    • name: string

    Returns ParamNodeDefinition

paramsFromSearch

paramsToSearch

parent

  • Creates a new instance of a parent node, which is used to retrieve the parent of a given node. The parent returns a NodeDefinition that is a parent in terms of the path in the graph. Imagine that there's a node you can access using a following ref: ref('deeply', 'nested', 'node'). If the node addressed by that ref used a parent it would have returned the same node as the node addressed by ref('deeply', 'nested').

    example

    Retrieve a value of a sibling

    import muster, { get, parent, ref } from '@dws/muster';
    
    const app = muster({
      something: get(parent(), 'other'),
      other: 'other value',
    });
    
    const something = await app.resolve(ref('something'));
    // something === 'other value'

    This example shows how to use the parent to retrieve the value of a sibling node.

    example

    Retrieve a sibling from a computed node

    import muster, { computed, get, parent, ref } from '@dws/muster';
    
    const app = muster({
      something: computed([], () =>
        get(parent(), 'other'),
      ),
      other: 'other value',
    });
    
    const something = await app.resolve(ref('something'));
    // something === 'other value'

    This example shows that the parent can be used within a computed.

    Returns ParentNodeDefinition

parseArg

parseArgument

parseBranches

parseChildOperations

parseContextDependency

parseContextIdParamName

  • parseContextIdParamName(contextId: string | symbol): string | undefined

parseFallbackGenerator

parseFallbackGenerator

parseFieldDefinition

parseFloat

  • Creates a new instance of a parseFloat node, which is used to convert values of a value to a float.

    example

    Convert string to a float

    import muster, { parseFloat, ref } from '@dws/muster';
    
    const app = muster({
      one: '1',
      two: 2,
      threeAndAHalf: '3.5'
    });
    
    const one = await app.resolve(parseFloat(ref('one')));
    // one === 1
    
    const two = await app.resolve(parseFloat(ref('two')));
    // two === 2
    
    const three = await app.resolve(parseFloat(ref('threeAndAHalf')));
    // three === 3.5

    This example shows how to use the parseFloat to convert a value of a value to a float.

    Parameters

    Returns ParseFloatNodeDefinition

parseGenericOperation

parseHandlerEvent

  • parseHandlerEvent<T, P, S, D, V, M, O, N, A>(fn: function): function

parseInt

  • Creates a new instance of a parseInt node, which is used to convert values of a value to an integer.

    example

    Convert string to an integer

    import muster, { parseInt, ref } from '@dws/muster';
    
    const app = muster({
      one: '1',
      two: 2,
    });
    
    const one = await app.resolve(parseInt(ref('one')));
    // one === 1
    
    const two = await app.resolve(parseInt(ref('two')));
    // two === 2
    
    const three = await app.resolve(parseInt('3'));
    // three === 3

    This example shows how to use the parseInt to convert a value of a value to an integer.

    Parameters

    Returns ParseIntNodeDefinition

parseNodeDependency

parseOperation

parseOperations

parseResetOperation

parseScenario

parseScenarioOperations

parseSetOperation

partial

  • Creates a new instance if the partial node, which can be used to create a partially applied functions. This node works with both named and positional arguments.

    example

    Bind positional arguments

    import muster, { action, call, partial, ref } from '@dws/muster';
    
    const app = muster({
      greet: action((name) => `Hello, ${name}!`),
      greetBob: partial(ref('greet'), ['Bob']),
    });
    
    await app.resolve(call('greetBob'));
    // === 'Hello, Bob!'
    
    await app.resolve(call('greet', ['Alice']));
    // === 'Hello, Alice!'
    
    await app.resolve(call('greetBob', ['Alice']));
    // === 'Hello, Bob!'

    This example shows how to use the partial node to partially apply the positional arguments. This method works with any node supporting the call operation (e.g. fn, apply, etc.).

    example

    Bind named argument

    import muster, { action, call, partial, ref } from '@dws/muster';
    
    const app = muster({
      greet: action(({ name }) => `Hello, ${name}!`),
      greetBob: partial(ref('greet'), { name: 'Bob' }),
    });
    
    await app.resolve(call('greetBob'));
    // === 'Hello, Bob!'
    
    await app.resolve(call('greet', { name: 'Alice' }));
    // === 'Hello, Alice!'
    
    await app.resolve(call('greetBob', { name: 'Alice' }));
    // === 'Hello, Bob!'

    This example shows how to use the partial node to partially apply named arguments. This method works with any node supporting the call operation (e.g. fn, apply, etc.).

    Parameters

    Returns PartialNodeDefinition

partitionAtIndex

  • partitionAtIndex<T>(items: Array<T>, splitStartIndex: number): [Array<T>, Array<T>]

pascalCase

  • pascalCase(text: string): string

pattern

pending

placeholder

pop

  • Creates an instance of an pop, which is a type of a graph node used when popping a last item from a mutable collection. It works in a similar way to Array.pop(...) function from JavaScript.

    example

    Pop a number from a mutable collection

    import muster, { arrayList, entries, query, ref, pop } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([3, 1, 2]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((numbers) => {
      console.log(numbers);
    });
    
    await app.resolve(pop(ref('numbers'))); // === 2
    await app.resolve(pop(ref('numbers'))); // === 1
    await app.resolve(pop(ref('numbers'))); // === 3
    await app.resolve(pop(ref('numbers'))); // === null
    await app.resolve(pop(ref('numbers'))); // === null
    
    // Console output:
    // [3, 1, 2]
    // [3, 1]
    // [3],
    // []

    This example shows how to use the pop node to remove last item from the mutable collection. The node resolves to a removed value or nil node, when there are no more items to be popped.

    example

    Pop a branch from a mutable collection

    import muster, { arrayList, entries, key, query, ref, pop } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { firstName: 'Lizzie', lastName: 'Ramirez' },
        { firstName: 'Charlotte', lastName: 'Schneider' },
        { firstName: 'Genevieve', lastName: 'Patrick' },
      ]),
    });
    
    app.resolve(query(ref('numbers'), entries({
      firstName: key('firstName'),
    }))).subscribe((people) => {
      console.log(people);
    });
    
    await app.resolve(pop(ref('people'))); // === { firstName: 'Genevieve', lastName: 'Patrick' }
    await app.resolve(pop(ref('people'))); // === { firstName: 'Charlotte', lastName: 'Schneider' }
    await app.resolve(pop(ref('people'))); // === { firstName: 'Lizzie', lastName: 'Ramirez' }
    await app.resolve(pop(ref('people'))); // === null
    await app.resolve(pop(ref('people'))); // === null
    
    // Console output:
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }, { firstName: 'Genevieve' }]
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }]
    // [{ firstName: 'Lizzie' }]
    // []

    Parameters

    Returns PopNodeDefinition

popOperation

pow

  • Creates a new instance of a pow node, which is a type of NodeDefinition used to compute the base to the exponent power for number-based values. The pow takes two arguments: base and exponent..

    example

    Power of two

    import muster, { pow, ref } from '@dws/muster';
    
    const app = muster({
      five: 5,
      two: 2,
    });
    
    const result = await app.resolve(
      pow(ref('five'), ref('two')),
    );
    // result === 25

    This example shows how to use pow node.

    Parameters

    Returns PowNodeDefinition

processObject

  • processObject(obj: any, visited: Set<any>): any

processResponse

property

  • Creates a new instance of a property node, which is used when extracting a value of a property from a pure JS object. It works in the same way as get from lodash.

    example

    Extract property from an object

    import muster, { property, value } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(
      property(
        value({ name: 'Bob', description: 'Some description' }),
        'name'
      ),
    );
    // === 'Bob'

    This example shows how to use the property to extract the value of a property from a pure JS object.

    example

    Extract nested property from an object

    import muster, { property, value } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(
      property(
        value({
          deeply: {
            nested: { name: 'Bob', description: 'Some description' },
          },
        }),
        ['deeply', 'nested', 'name']
      ),
    );
    // === 'Bob'

    This example shows how to use the property to extract the value of a deeply nested property from a pure JS object.

    example

    Extract property from a node in the graph

    import muster, { property, ref, value } from '@dws/muster';
    
    const app = muster({
      user: value({
        name: 'Bob',
        description: 'Some description',
      }),
    });
    
    await app.resolve(property(ref('user'), 'name'));
    // === 'Bob'

    This example shows that the property can operate on any kind of node that resolves to a value.

    Parameters

    Returns PropertyNodeDefinition

proxy

push

  • Creates an instance of an push, which is a type of a graph node used when pushing a new item into a mutable collection. It works in a similar way to Array.push(...) function from JavaScript.

    example

    Push a number to a mutable collection

    import muster, { arrayList, entries, push, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([1, 2, 3]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(push(ref('numbers'), 5));
    
    // Console output:
    // [1, 2, 3]
    // [1, 2, 3, 5]

    This example shows how to add a new item at the end of a mutable collection.

    example

    Push a branch to a mutable collection

    import muster, { arrayList, entries, key, push, query, ref, toNode } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { firstName: 'Lizzie', lastName: 'Ramirez' },
        { firstName: 'Charlotte', lastName: 'Schneider' },
      ]),
    });
    
    app.resolve(query(ref('people'), entries({
      firstName: key('firstName'),
    }))).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(
      push(ref('people'), toNode({ firstName: 'Genevieve', lastName: 'Patrick' })),
    );
    
    // Console output:
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }]
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }, { firstName: 'Genevieve' }]

    This example shows how to add a new branch at the end of a mutable collection.

    Parameters

    Returns PushNodeDefinition

pushOperation

pushStackItem

  • pushStackItem<T>(value: T, stack: Stack<T>): Stack<T>

query

  • Creates an instance of a query node, which is a node used to request values from multiple NodeDefinitions at a time. This node is used internally by Muster-React when creating bindings between components and the graph. See Muster-React for more information.

    By default, the query waits for every field to resolve to a non-dynamic node. This behaviour can be modified through the use of the isPending and the defer.

    A query resolves into a tree, an array or a value (depending on the type of the query made). These can be easily converted into plain JS objects with the valueOf helper. This conversion is reversible through the use of toNode helper.

    example

    Basic query

    import muster, { key, query, root, valueOf } from '@dws/muster';
    
    const app = muster({
      firstName: 'Rosalind',
      lastName: 'Franklin',
      dateOfBirth: 1948,
    });
    
    const user = await app.resolve(query(root(), {
      userFirstName: key('firstName'),
      lastName: key('lastName'),
    }));
    // user = {
    //   userFirstName: 'Rosalind',
    //   lastName: 'Franklin',
    // }

    This example shows how to use a query to request two NodeDefinition at the same time. The query call consists of: the first argument which defines the graph starting point from which query should begin the traversal; and the second argument, an object (implicitly cast to a fields) which defines a map of fields to retrieve from the graph. The name of each property in that map corresponds to the name in the output tree. Note that this name does not have to be the same as the name in the key on the right of that property. Take the firstName graph node and its corresponding userFirstName name in the query. The ability to override the name of a node is useful especially when a given NodeDefinition can be accessed in more than one way. This behaviour is used extensively by the proxy, and by extension the remote, when building a query to a remote node.

    The key used in this query defines the name of a given node in the graph. Additionally, the key can define a map of child nodes to retrieve from that node. See the "Getting values of nested nodes" example for more information.

    A query resolves into a combination of trees, arrays and values. This means an output of one query can be used as an input for another NodeDefinition and even another query.

    example

    Getting async values

    import muster, { fromPromise, key, query, root } from '@dws/muster';
    
    let resolvePromise1;
    const app = muster({
      name: 'sync name',
      asyncName: fromPromise(() =>
        new Promise((res) => resolvePromise1 = res)
          .then(() => 'async name'),
      ),
    });
    
    console.log('Making the query');
    app.resolve(query(root(), {
      name: key('name'),
      asyncName: key('asyncName'),
    })).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Resolving the promise');
    resolvePromise1();
    
    // Console output:
    // Making the query
    // Resolving the promise
    // {
    //   name: 'sync name',
    //   asyncName: 'async name',
    // }

    The query by default waits for every part of the query to resolve to a non-pending and non-dynamic value. This example demonstrates this behaviour with the help of fromPromise. Note that the query output gets logged only once - after the promise is resolved. Muster can also mark certain parts of the query with defers. This instructs Muster to return the query result even if that part of the query is loading. See the "Defer part of the query" example for more information.

    example

    Getting values of nested nodes

    import muster, { key, query, root } from '@dws/muster';
    
    const app = muster({
      user: {
        firstName: 'Rosalind',
        lastName: 'Franklin',
      },
    });
    
    const user = await app.resolve(query(root(), {
      user: key('user', {
        firstName: key('firstName'),
      }),
    }));
    // user = {
    //   user: {
    //     firstName: 'Rosalind',
    //   },
    // }

    The query can extract values from nested NodeDefinitions. As shown in the previous example, the query factory function performs an implicit conversion to a fields. This saves developers from having to explicitly write unnecessarily verbose code. The same functionality is available in the key. When the factory is called with a pure JS object, it will recursively cast it to a fields.

    Sometimes, the second argument to the key won't be a pure JS object. For example, when a developer wants to get items from a collection. fields lets the query know that a target NodeDefinition is expected to be a container-like node. This assumption breaks apart when requesting a collection. To request items from collections, one has to make a query with an entries instead of a fields. See the "Getting atomic items from a collection" example to find out more.

    example

    Getting atomic items from a collection

    import muster, { entries, key, query, root } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4],
    });
    
    const numbers = await app.resolve(query(root(), {
      numbers: key('numbers', entries()),
    }));
    // numbers = {
    //   numbers: [1, 2, 3, 4],
    // }

    An entries can be provided instead of a fields to instruct the query to retrieve all items from a given graph node. In this example, we had it easy: every item is an atomic value. The fun with querys and collections does not end here. See the "Getting specific fields from items" example to learn more about selecting certain fields from items.

    example

    Getting specific fields from items

    import muster, { entries, key, query, ref } from '@dws/muster';
    
    const app = muster({
      books: [
        { name: 'The Expeditionary Force', author: 'Craig Alanson' },
        { name: 'Fear The Sky', author: 'Stephen Moss' },
        { name: 'After It Happened', author: 'Devon Ford' },
      ],
    });
    
    const bookNames = await app.resolve(query(ref('books'), entries({
      name: key('name'),
    })));
    // bookNames = [
    //   { name: 'The Expeditionary Force' },
    //   { name: 'Fear The Sky' },
    //   { name: 'After It Happened' },
    // ]

    In this example, apart from getting just a selected field from each item in the collection, we demonstrated another feature of the query: changing its starting point. In all previous examples, we've used a root as the starting point of the query, but this time to make the output shorter we've changed it to a books collection.

    example

    Creating setters

    import muster, {
      createSetter,
      key,
      query,
      root,
      variable,
    } from '@dws/muster';
    
    const app = muster({
      name: variable('initial'),
    });
    
    console.log('Making a query for `name`');
    app.resolve(query(root(), { name: key('name') })).subscribe((result) => {
      console.log(result);
    });
    
    console.log('Making a query for setter function');
    const result = await app.resolve(query(root(), {
      setName: createSetter('name'),
    }));
    
    console.log('Calling a setter');
    result.setName('updated');
    
    // Console output:
    // Making a query for `name`
    // initial
    // Making a query for setter function
    // Calling a setter
    // updated

    This example shows how a query can be used when there's a need for imperative call to a set method. This setter function can be used, for example, when integrating with view frameworks such as React, Vue etc. Muster-React uses this way of creating setters extensively. Similarly, there's a createCaller node which allows for imperative calls to actions.

    createSetters and createCallers should be used only when the output of the query is used outside the "Muster world". Inside Muster code, using calls applys and sets is recommended for these kinds of actions.

    example

    Defer part of a query

    import muster, { defer, fromPromise, key, query, root } from '@dws/muster';
    
    let resolvePromise2;
    const app = muster({
      name: 'sync name',
      asyncName: fromPromise(() =>
        new Promise((res) => resolvePromise2 = res)
          .then(() => 'async name'),
      ),
    });
    
    console.log('Requesting the query');
    app.resolve(query(root(), {
      name: key('name'),
      asyncName: defer('asyncName'),
    })).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Resolving the promise');
    resolvePromise2();
    
    // Console output:
    // Requesting the query
    // {
    //   name: 'sync name',
    //   asyncName: null,
    // }
    // Resolving the promise
    // {
    //   name: 'sync name',
    //   asyncName: 'async name',
    // }

    This example demonstrates how to instruct a query to return the output of its query even if a given NodeDefinition is in a pending state. The query is built with a defer. This example uses a shorthand syntax for the defer(...) node. Internally, the node converts the argument to a key:

    import { defer, key } from '@dws/muster';
    
    defer('asyncName');
    // is equivalent to
    defer(key('name'));

    The defer also enables the defer part of the query to return a previously loaded (stale) value of the target node. See the "Defer with previous value" example for more information.

    example

    Check if defer part of the query is loading

    import muster, {
      defer,
      fromPromise,
      isPending,
      key,
      query,
      root,
    } from '@dws/muster';
    
    let resolvePromise3;
    const app = muster({
      name: 'sync name',
      asyncName: fromPromise(() =>
        new Promise((res) => resolvePromise3 = res)
          .then(() => 'async name'),
      ),
    });
    
    console.log('Requesting the query');
    app.resolve(query(root(), {
      name: key('name'),
      asyncName: defer('asyncName'),
      isLoadingAsyncName: isPending('asyncName'),
    })).subscribe((res) => {
      console.log(res);
    });
    
    console.log('Resolving the promise');
    resolvePromise3();
    
    // Console output:
    // Requesting the query
    // {
    //   name: 'sync name',
    //   asyncName: null,
    //   isLoadingAsyncName: true,
    // }
    // Resolving the promise
    // {
    //   name: 'sync name',
    //   asyncName: 'async name',
    //   isLoadingAsyncName: false,
    // }

    This example presents the use of the isPending. When used in a query, this node checks if a part of the query is currently loading. Similarly to the defer, the isPending factory function implicitly converts its argument to a key.

    import { isPending, key } from '@dws/muster';
    
    isPending('asyncName');
    // is equivalent to
    isPending(key('asyncName'))

    Parameters

    Returns QueryNodeDefinition

querySet

querySetCallOperation

querySetCatchError

querySetDefer

querySetGetChildOperation

querySetGetItemsOperation

querySetIsPending

querySetOperation

querySetResult

querySetSetOperation

queueCachedAction

queueInvalidation

  • queueInvalidation(store: Store, cachedAction: CachedAction, invokeLifecycleMethod: boolean): void

quote

  • Creates a new instance of the quote node, which is a node used as a wrapper for different nodes. It is useful when there's a need to prevent a node from being unintentionally resolved/evaluated by muster.

    example

    Creating a quote node `js import muster, { computed, quote } from '@dws/muster';

    const app = muster({});

    // Without quote node await app.resolve(computed( [computed([], () => 'Some value')], (node) => { // node === 'Some value' // perform some logic }, ));

    // With quote node await app.resolve(computed( [quote(computed([], () => 'Some value'))], (node) => { // node === quote(computed([], () => 'Some value')) // perform some logic }, )); `.

    Parameters

    Returns QuoteNodeDefinition

recursive

  • recursive<T, V>(factory: function): Matcher<T, V>

reduce

ref

  • A helper function used for locating nodes in the muster graph.

    After a value, this is the most useful node in the whole of muster. It can be used in the dependencies of a computed, to link parts of the graph, as an output of a computed, etc.

    A path used in the ref does not have to be a string. It can be any graph node that resolves to a non-dynamic node, e.g. another ref that points to a value, a ref to a computed that returns a value, a value storing a numeric value, a value storing an object, etc.

    In most cases, a ref is defined as a path from the root of the graph. This behaviour can be changed by setting the root property to a different NodeDefinition. See the "Overriding a root node" example for more on this.

    Internally every ref is converted to a series of nested gets. See the get documentation for more information.

    Parameters

    Returns NodeDefinition

    NodeDefinition

  • A helper function used for locating nodes in the muster graph.

    After a value, this is the most useful node in the whole of muster. It can be used in the dependencies of a computed, to link parts of the graph, as an output of a computed, etc.

    A path used in the ref does not have to be a string. It can be any graph node that resolves to a non-dynamic node, e.g. another ref that points to a value, a ref to a computed that returns a value, a value storing a numeric value, a value storing an object, etc.

    In most cases, a ref is defined as a path from the root of the graph. This behaviour can be changed by setting the root property to a different NodeDefinition. See the "Overriding a root node" example for more on this.

    Internally every ref is converted to a series of nested gets. See the get documentation for more information.

    Parameters

    Returns NodeDefinition

    NodeDefinition

  • A helper function used for locating nodes in the muster graph.

    After a value, this is the most useful node in the whole of muster. It can be used in the dependencies of a computed, to link parts of the graph, as an output of a computed, etc.

    A path used in the ref does not have to be a string. It can be any graph node that resolves to a non-dynamic node, e.g. another ref that points to a value, a ref to a computed that returns a value, a value storing a numeric value, a value storing an object, etc.

    In most cases, a ref is defined as a path from the root of the graph. This behaviour can be changed by setting the root property to a different NodeDefinition. See the "Overriding a root node" example for more on this.

    Internally every ref is converted to a series of nested gets. See the get documentation for more information.

    Parameters

    Returns NodeDefinition

    NodeDefinition

regex

registerMusterType

  • registerMusterType<N>(name: string, musterTypeProps: Omit<MusterType<N>, "name">): void

registerNodeType

  • registerNodeType(nodeType: NodeType): void

registerOperationType

registerTypeHasher

  • registerTypeHasher<T>(type: Matcher<any> | function, hasher: T): T

relative

releaseCachedActionResult

releaseCachedNode

releaseCachedNodeAction

releaseCachedScope

releaseNode

releaseNodeAction

releaseScope

  • releaseScope(store: Store, scope: Scope): number

remote

remoteError

removeActionFromCache

removeConsecutiveDuplicates

  • removeConsecutiveDuplicates<T>(array: Array<T>): Array<T>

removeHashSetItem

removeItem

  • Creates a new instance of the removeItem node, which is a type of a NodeDefinition used when removing a specific item from a collection supporting removeItemOperation.

    example

    Remove the last item from a collection

    import muster, { arrayList, entries, last, query, ref, removeItem } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { name: 'Sarah' },
        { name: 'Jane' },
        { name: 'Kate' },
      ]),
    });
    
    app.resolve(query(ref('people'), entries({ name: true }))).subscribe((people) => {
      console.log('People:', people);
    });
    
    console.log('Removing last entry');
    await app.resolve(removeItem(ref('people'), ref('people', last())));
    
    // Console output:
    // People: [{ name: 'Sarah' }, { name: 'Jane' }, { name: 'Kate' }]
    // Removing last entry
    // People: [{ name: 'Sarah' }, { name: 'Jane' }]
    example

    Remove person with name Jane

    import muster, { applyTransforms, arrayList, eq, entries, filter, get, head, query, ref, removeItem } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { name: 'Sarah' },
        { name: 'Jane' },
        { name: 'Kate' },
      ]),
    });
    
    app.resolve(query(ref('people'), entries({ name: true }))).subscribe((people) => {
      console.log('People:', people);
    });
    
    console.log('Removing Jane');
    await app.resolve(removeItem(ref('people'), head(applyTransforms(ref('people'), [
      filter((person) => eq(get(person, 'name'), 'Jane'))
    ]))));
    
    // Console output:
    // People: [{ name: 'Sarah' }, { name: 'Jane' }, { name: 'Kate' }]
    // Removing Jane
    // People: [{ name: 'Sarah' }, { name: 'Kate' }]

    Parameters

    Returns RemoveItemNodeDefinition

removeItemAt

  • Creates an instance of an [[remoteItemAt]] node, which is a type of a graph node used when inserting an item into a mutable collection at a specific index.

    example

    Remove a number from a mutable collection

    import muster, { arrayList, entries, query, ref, removeItemAt } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([1, 2, 3]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(removeItemAt(ref('numbers'), 1));
    
    // Console output:
    // [1, 2, 3]
    // [1, 3]

    This example shows how to remove item at a specific index from a mutable collection.

    example

    Remove a branch from a mutable collection

    import muster, { arrayList, entries, key, query, ref, removeItemAt, toNode } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { firstName: 'Lizzie', lastName: 'Ramirez' },
        { firstName: 'Charlotte', lastName: 'Schneider' },
      ]),
    });
    
    app.resolve(query(ref('people'), entries({
      firstName: key('firstName'),
    }))).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(
      removeItemAt(ref('people'), 1),
    );
    
    // Console output:
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }]
    // [{ firstName: 'Lizzie' }]

    This example shows how to remove a branch at a specific index from a mutable collection.

    Parameters

    Returns RemoveItemAtNodeDefinition

removeItemAtOperation

removeItemOperation

removeItems

  • Creates an instance of a removeItems node, which is used to remove all items from a mutable collection that match the provided predicate.

    The predicate can be any callable node (e.g. fn() or action() – the default is fn()), which will be invoked with a single parameter (the list item), and must return a node that resolves to a boolean value() node that determines whether to remove that item. The predicate will be invoked once for each item in the collection.

    example

    Remove all items from a mutable collection that match the provided predicate

    import muster, { arrayList, entries, get, query, ref, removeItems, fn } from '@dws/muster';
    
    const app = muster({
      tasks: arrayList([
        { description: 'First task', completed: true },
        { description: 'Second task', completed: true },
        { description: 'Third task', completed: false },
      ]),
    });
    
    app.resolve(query(ref('tasks'), entries({ description: true }))).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(removeItems(ref('tasks'), (item) => get(item, 'completed')));
    
    // Console output:
    // [{ description: 'First task' }, { description: 'Second task' }, { description: 'Third task' }]
    // [{ description: 'Third task' }]

    Parameters

    Returns RemoveItemsNodeDefinition

removeItemsOperation

removeNodeFromCache

removeScopeFromCache

  • removeScopeFromCache(store: Store, scope: Scope): void

replace

  • Creates a new instance of a replace node, which is used for replacing a specific pattern in a given string with another string. The node expects the subject, pattern and replacement pattern to be a value containing a string value. It resolves to a value with a string value.

    example

    Replace a string

    import muster, { replace } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(replace(
      'world',
      'Bob',
      'Hello, world',
    ));
    // === 'Hello, Bob'

    Parameters

    Returns ReplaceNodeDefinition

replaceContextWithValue

  • replaceContextWithValue(obj: any, argName: string, value: any): any

requestOperation

reset

resetOperation

resetVariableNode

resetVariablesInScope

resolve

resolveChildNode

resolveFields

resolveGetChildOperation

resolveGetChildOperation_children

resolveGetItemsOperation

resolveGetItemsOperation_getItems

resolveGetItemsOperation_processItems

resolveIteratorResult

resolveList

resolveListItems

resolveOperation

resolveOperations

resolveQuerySetCallOperation

resolveQuerySetCatchError

resolveQuerySetDefer

resolveQuerySetIsPending

resolveQuerySetOperation

resolveQuerySetOperation_children

resolveQuerySetSetOperation

resolveResetResponse

resolveSetResponse

resolveShallow

resolveSingleKey

resolveTransaction

resolveTransaction

result

retainCachedNode

retainCachedNodeAction

retainNode

retainNodeAction

retainScope

retrieveCachedAction

retrieveNodeCache

retrieveScopeCache

returnPending

root

  • Creates a new instance of a root node, which is used when you want to get the instance of the root graph node. Resolving this node gets the top-most node of the graph.

    example

    Get the root node

    import muster, { computed, root, value } from '@dws/muster';
    
    const app = muster(value('World'));
    
    const greeting = await app.resolve(
      computed([root()], (name) => `Hello, ${name}`),
    );
    // greeting === 'Hello, World'

    This example shows how to use the root to get access to the root node of the graph.

    Returns RootNodeDefinition

round

  • Creates a new instance of a round node, which is a type of a NodeDefinition used when rounding a number to the nearest integer. It works in the same way as the Math.round from JavaScript.

    example

    Round the value

    import muster, { round, ref } from '@dws/muster';
    
    const app = muster({
      fivePointThree: 5.3,
      fivePointSeven: 5.7,
    });
    
    await app.resolve(round(5));
    // === 5
    
    await app.resolve(round(5.2));
    // === 5
    
    await app.resolve(round(5.6));
    // === 6
    
    await app.resolve(round(ref('fivePointThree')));
    // === 5
    
    await app.resolve(round(ref('fivePointSeven')));
    // === 6

    Parameters

    Returns RoundNodeDefinition

safelyGetValueFromResponse

sample

sanitize

  • sanitize(value: any): any

sanitizeActionCache

sanitizeCachedAction

sanitizeChildren

sanitizeChildren

sanitizeFallback

sanitizeFallback

sanitizeFallback

sanitizeFallback

sanitizeGraphAction

sanitizeGraphNode

sanitizeGraphOperation

sanitizeGraphOperation

sanitizeGraphOperationProperties

  • sanitizeGraphOperationProperties<T, P, S>(operation: GraphOperation<T, P, S>): S

sanitizeGraphOperationProperties

  • sanitizeGraphOperationProperties<T, P, S>(operation: GraphOperation<T, P, S>): S

sanitizeMetadata

  • sanitizeMetadata(value: any): any

sanitizeMusterType

sanitizeMusterTypeMetadata

sanitizeNode

sanitizeNodeDefinition

sanitizeNodeProperties

  • sanitizeNodeProperties<T, P, S, D, V>(node: NodeDefinition<T, P, S, D, V>): V

sanitizeNodeProperties

  • sanitizeNodeProperties<T, P, S, D, V>(node: NodeDefinition<T, P, S, D, V>): V

sanitizeObject

  • sanitizeObject(obj: any): any

sanitizeObject

  • sanitizeObject(value: any, visited?: Set<any>): any

saveHash

scope

  • Creates a new instance of a scope node, which is used when to isolate part of the muster graph from the rest. The nodes from a scope are still accessible from the parent scope, but the nodes from within the scope have no way of accessing anything from the parent scope. By default, the scope also isolates the scope from external events and prevents the events dispatched in this scope leaving it. The behaviour of isolating scope from events dispatched in the parent scope can be overwritten with the help of the redispatch property. See the dispatch to learn more about event dispatching and how to configure the event re-dispatching.

    Nodes living in the scope have no access to the nodes from the parent scope so any dependencies must be injected to the scope as part of the context definition.

    example

    Simple scope

    import muster, { ref, scope } from '@dws/muster';
    
    const app = muster({
      nested: scope({
        value: 'Hello world',
      }),
    });
    
    const result = await app.resolve(ref('nested', 'value'));
    // result === 'Hello world'

    This example shows how to create a very simple scope with a single branch containing a value leaf. This leaf can be accessed in the same way as if the scope was a normal branch.

    example

    References inside of the scope

    import muster, { ref, scope } from '@dws/muster';
    
    const app = muster({
      greeting: 'Hello, world',
      nested: scope({
        greeting: 'Hello, Bob',
        refToGreeting: ref('greeting'),
      }),
    });
    
    const result = await app.resolve(ref('nested', 'greeting'));
    // result === 'Hello, Bob'

    This example shows how addressing changes within a given scope. Normally, the ref('greeting') would have returned a value('Hello, world') but a scope changes the root of the graph. This means that any reference within a scope can reference only the paths defined within a given scope.

    example

    Injecting nodes to a scope

    import muster, { context, ref, scope } from '@dws/muster';
    
    const app = muster({
      greeting: 'Hello, world',
      nested: scope({
        greeting: context('message'),
      }, {
        message: ref('greeting'),
      }),
    });
    
    const result = await app.resolve(ref('nested', 'greeting'));
    // result === 'Hello, world'

    In order to be able to use nodes from outside a given scope you have to inject them to the scope at creation time. These nodes can then be accessed from the context with the use of the context.

    Parameters

    Returns ScopeNodeDefinition

sentenceCase

  • Creates a new instance of a sentenceCase node, which is used when converting a string to a sentence case string. The node expects the subject to be a value that contains a string value. It works in a similar way to the upperFirst function from lodash.

    example

    Convert string to upper case

    import muster, { sentenceCase } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(sentenceCase('hello world'));
    // === 'Hello world'
    
    await app.resolve(sentenceCase('Hello World'));
    // === 'Hello World'
    
    await app.resolve(sentenceCase('hello WORLD'));
    // === 'Hello WORLD'

    Parameters

    Returns SentenceCaseNodeDefinition

serialize

  • serialize(value: any): string
  • A helper function used for serializing the GraphNode to a JSON that can be safely send to the remote or back to the client. It uses a node-specific implementation of sanitizer to figure out how best to represent the node as JSON.

    Parameters

    • value: any

    Returns string

serializeMetadata

series

  • Creates a new instance of a series node, which is used when you need to resolve a series of nodes. You can think of this node as of a list of statements to be executed, and the last statement being a return statement. The statements are executed one after another.

    example

    Resolve a series

    import muster, { series, set, value, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('initial name'),
      description: variable('initial description'),
    });
    
    const result = await app.resolve(series([
      set('name', 'updated name'),
      set('description', 'updated description'),
      value(true),
    ]));
    // result === true

    This example shows how to use the series to combine multiple operations. One thing to remember is that the operations are executed in order so one failing operation will prevent those following from running.

    example

    Failing operation in the series

    import muster, { computed, error, ref, series } from '@dws/muster';
    
    const app = muster({
      first: computed([], () => {
        console.log('Computing first');
        return 1;
      }),
      second: computed([], () => {
        console.log('Computing second');
        throw new Error('Boom!');
      }),
      third: computed([], () => {
        console.log('Computing third');
        return 3;
      }),
    });
    
    const result = await app.resolve(series([
      ref('first'),
      ref('second'),
      ref('third'),
    ]));
    // result === 'Boom!'
    
    // Console output:
    // Computing first
    // Computing second

    This example shows what happens with the series when one of the nodes in the series returns an error. From the console output you can deduce that the third node is never resolved.

    Parameters

    Returns SeriesNodeDefinition

set

  • Creates instance of the set node, which allows for setting values of certain nodes, e.g. variable, fromPromise and placeholder.

    The output of a set is the same as a value property. See the "Setting a variable" example for more information.

    When resolving a set against an asynchronous node like fromPromise, the value from the resolver will wait for fromPromise to update to new value, then emit value from set. See the "Setting asynchronous nodes" example for more information.

    This node does not resolve the value before setting the value of the settable node. To resolve the value before setting the value of the settable node use the setResult node.

    example

    Setting a variable

    import muster, { set, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
    });
    
    console.log('Setting variable');
    app.resolve(set('name', 'Jane')).subscribe((result) => {
      // result === 'Jane'
      console.log('Set resolved');
    });
    console.log('End');
    
    // Console output:
    // Setting variable
    // Set resolved
    // End

    This example demonstrates how a set can be used to update the value of a variable. The set also returns the value set to the target node. See the variable documentation to learn more about the lifecycle of variables in Muster.

    example

    Setting asynchronous nodes

    import muster, { fromPromise, set } from '@dws/muster';
    
    let savedName = 'Bob';
    
    const app = muster({
      name: fromPromise({
        get: () => Promise.resolve(savedName),
        set: (props, newValue) => new Promise((resolve) => {
          // newValue is a ValueNode
          savedName = newValue;
          resolve();
        }),
      }),
    });
    
    console.log('Setting variable');
    app.resolve(set('name', 'Jane')).subscribe((result) => {
      // result === 'Jane'
      console.log('Set resolved');
    });
    console.log('End');
    
    // Console output:
    // Setting variable
    // End
    // Set resolved

    This example demonstrates that a set waits for the target value to be updated before returning a result. See the fromPromise for more information on how to make asynchronous API requests.

    The fact that the set waits for the operation to finish is very useful when using it as part of a series, fn or action.

    Parameters

    Returns SetNodeDefinition

  • Parameters

    Returns SetNodeDefinition

  • Parameters

    Returns SetNodeDefinition

  • Parameters

    Returns SetNodeDefinition

setNodeData

setNodeState

setOperation

setResult

  • Creates instance of the setResult node, which allows for setting values of certain nodes, e.g. variable, fromPromise and placeholder. Compared to the set node, the setResult node first resolves the value to a static node before setting the settable node.

    The output of a setResult is the same as a value property. See the "Setting a variable" example for more information.

    When resolving a setResult against an asynchronous node like fromPromise, the value from the resolver will wait for fromPromise to update to new value, then emit value from setResult. See the "Setting asynchronous nodes" example for more information.

    example

    Setting a variable

    import muster, { setResult, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
    });
    
    console.log('Setting variable');
    app.resolve(setResult('name', 'Jane')).subscribe((result) => {
      // result === 'Jane'
      console.log('SetResult resolved');
    });
    console.log('End');
    
    // Console output:
    // Setting variable
    // SetResult resolved
    // End

    This example demonstrates how a setResult can be used to update the value of a variable. The setResult also returns the value setResult to the target node. See the variable documentation to learn more about the lifecycle of variables in Muster.

    example

    Setting asynchronous nodes

    import muster, { fromPromise, setResult } from '@dws/muster';
    
    let savedName = 'Bob';
    
    const app = muster({
      name: fromPromise({
        get: () => Promise.resolve(savedName),
        set: (props, newValue) => new Promise((resolve) => {
          // newValue is a ValueNode
          savedName = newValue;
          resolve();
        }),
      }),
    });
    
    console.log('Setting variable');
    app.resolve(setResult('name', 'Jane')).subscribe((result) => {
      // result === 'Jane'
      console.log('SetResult resolved');
    });
    console.log('End');
    
    // Console output:
    // Setting variable
    // End
    // SetResult resolved

    This example demonstrates that a setResult waits for the target value to be updated before returning a result. See the fromPromise for more information on how to make asynchronous API requests.

    The fact that the setResult waits for the operation to finish is very useful when using it as part of a series, fn or action.

    example

    Computing value before saving

    import muster, { format, ref, setResult, variable } from '@dws/muster';
    
    const app = muster({
      url: variable('/'),
    });
    
    console.log('Getting URL');
    app.resolve(ref('url')).subscribe((result) => {
      console.log('URL:', result);
    });
    
    console.log('Setting URL');
    await app.resolve(setResult('url', format('/article/${id}', {
      id: 'test-id',
    })));
    
    // Console output:
    // Getting URL
    // URL: /
    // Setting URL
    // URL: /article/test-id

    This example shows how to use the setResult node to resolve the value before setting the node.

    Parameters

    Returns SetResultNodeDefinition

  • Parameters

    Returns SetResultNodeDefinition

  • Parameters

    Returns SetResultNodeDefinition

  • Parameters

    Returns SetResultNodeDefinition

setTransformMiddlewares

setUnitTestMatcher

  • setUnitTestMatcher(matcher: function): void

shape

share

shift

  • Creates an instance of an shift, which is a type of a graph node used when shifting a last item from a mutable collection. It works in a similar way to Array.shift(...) function from JavaScript.

    example

    Shift a number from a mutable collection

    import muster, { arrayList, entries, query, ref, shift } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([3, 1, 2]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((numbers) => {
      console.log(numbers);
    });
    
    await app.resolve(shift(ref('numbers'))); // === 3
    await app.resolve(shift(ref('numbers'))); // === 1
    await app.resolve(shift(ref('numbers'))); // === 2
    await app.resolve(shift(ref('numbers'))); // === null
    await app.resolve(shift(ref('numbers'))); // === null
    
    // Console output:
    // [3, 1, 2]
    // [1, 2]
    // [2],
    // []

    This example shows how to use the shift node to remove last item from the mutable collection. The node resolves to a removed value or nil node, when there are no more items to be shifting.

    example

    Shift a branch from a mutable collection

    import muster, { array, entries, key, query, ref, shift } from '@dws/muster';
    
    const app = muster({
      people: array([
        { firstName: 'Lizzie', lastName: 'Ramirez' },
        { firstName: 'Charlotte', lastName: 'Schneider' },
        { firstName: 'Genevieve', lastName: 'Patrick' },
      ]),
    });
    
    app.resolve(query(ref('numbers'), entries({
      firstName: key('firstName'),
    }))).subscribe((people) => {
      console.log(people);
    });
    
    await app.resolve(shift(ref('people'))); // === { firstName: 'Lizzie', lastName: 'Ramirez' }
    await app.resolve(shift(ref('people'))); // === { firstName: 'Charlotte', lastName: 'Schneider' }
    await app.resolve(shift(ref('people'))); // === { firstName: 'Genevieve', lastName: 'Patrick' }
    await app.resolve(shift(ref('people'))); // === null
    await app.resolve(shift(ref('people'))); // === null
    
    // Console output:
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }, { firstName: 'Genevieve' }]
    // [{ firstName: 'Charlotte' }, { firstName: 'Genevieve' }]
    // [{ firstName: 'Genevieve' }]
    // []

    Parameters

    Returns ShiftNodeDefinition

shiftOperation

skip

  • Creates a new instance of the skip node, which is a collection transform used to bypass a specified number of elements in a collection and then returns the remaining elements.

    example

    Skip 3 items

    import muster, { applyTransforms, entries, query, ref, skip } from '@dws/muster';
    
    const app = muster({
      numbers: applyTransforms(
        [1, 2, 3, 4, 5],
        [skip(3)],
     ),
    });
    
    await app.resolve(query(ref('numbers'), entries())); // === [4, 5]

    This example shows how to skip 3 items from the collection.

    example

    Skip a number of items defined by a variable

    import muster, { applyTransforms, entries, query, ref, skip, variable  } from '@dws/muster';
    
    const app = muster({
      skipCount: variable(4),
      numbers: applyTransforms(
        [1, 2, 3, 4, 5],
        [skip(ref('skipCount'))],
      ),
    });
    
    await app.resolve(query(ref('numbers'), entries())); // === [5]

    This example shows that the offset can also be defined as a ref to another node in the graph. One thing to remember is that the offset node must resolve to a value node containing a positive integer value. An error will be returned when the condition is not met.

    Parameters

    Returns SkipNodeDefinition

skipRepeatedValues

  • skipRepeatedValues<T>(equality: function, stream: Stream<T>): Stream<T>
  • Type parameters

    • T

    Parameters

    • equality: function
        • (value: T, previousValue: T): boolean
        • Parameters

          • value: T
          • previousValue: T

          Returns boolean

    • stream: Stream<T>

    Returns Stream<T>

slice

  • Creates a new instance of a slice node, which is a type of collection transform used when limiting the number of items returned from a collection. It lets you skip a number of items from the start and define the number of items to return. One use case for this node is returning paginated items. It behaves in a similar way to the JavaScript's Array.slice() method.

    The slice allows for three forms of specifying the range:

    • slice({ offset: number, length: number })
    • slice({ from: number, to: number })
    • slice({ begin: number, end: number })
    example

    Simple range selection

    import muster, { entries, key, query, ref, slice, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const firstTwoNumbers = await app.resolve(query(ref('numbers'), withTransforms([
      slice({ offset: 0, length: 2 }),
    ], entries())));
    // firstTwoNumbers = [1, 2]
    
    const otherTwoNumbers = await app.resolve(query(ref('numbers'), withTransforms([
      slice({ offset: 2, length: 2 }),
    ], entries())));
    // otherTwoNumbers = [3, 4]

    This example shows how to take two items out of a collection with the help of a slice.

    example

    Paginated collection

    import muster, {
      applyTransforms,
      entries,
      key,
      multiply,
      query,
      ref,
      set,
      slice,
      variable,
    } from '@dws/muster';
    
    const app = muster({
      pageSize: 2,
      pageIndex: variable(0),
      pageOffset: multiply(ref('pageIndex'), ref('pageSize')),
      numbers: applyTransforms(
        [1, 2, 3, 4, 5, 6],
        [slice({ offset: ref('pageOffset'), length: ref('pageSize') })]
      ),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((items: any) => {
      console.log(items);
    });
    
    console.log('Changing page index to 1');
    await app.resolve(set('pageIndex', 1));
    
    // Console output:
    // [1, 2]
    // Changing page index to 1
    // [3, 4]

    This example shows how to implement the simple pagination of a local collection.

    Parameters

    Returns SliceNodeDefinition

some

  • A helper function that creates a NodeDefinition capable of checking if a given node exists in a target collection.

    example

    Check if contains a number

    import muster, { some, fn, gt, lt, ref } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3],
    });
    
    await app.resolve(some(ref('numbers'), 1)); // === true
    await app.resolve(some(ref('numbers'), 4)); // === false
    await app.resolve(some(ref('numbers'), fn((item) => gt(item, 0)))); // === true
    await app.resolve(some(ref('numbers'), fn((item) => lt(item, 1)))); // === false

    Parameters

    Returns NodeDefinition

sort

  • Creates a new instance of a sort node, which is a type of collection transform used to sort the output of a collection. The sort order takes an array of sortOrders which define the ordering of the sort. The items of the order array are assuming a descending order of priority, with the first item having the highest priority and the last one having the lowest.

    For example, given the following items:

    Make Model Year
    Mercedes C 63 AMG 2017
    Mercedes A 2009
    Audi R8 2013
    Audi A4 2018
    Toyota Corolla 2016
    When the sort order is defined as:
    1. Sort by `Make` ascending
    2. Sort by `Year` descending
    The table should look like:
    Make Model Year
    Audi A4 2018
    Audi R8 2013
    Mercedes C 63 AMG 2017
    Mercedes A 2009
    Toyota Corolla 2016

    Sort order can be defined with the help of two helper functions:

    example

    Sorting numbers

    import muster, {
      ascending,
      descending,
      entries,
      query,
      ref,
      sort,
      withTransforms,
    } from '@dws/muster';
    
    const app = muster({
      numbers: [5, 3, 2, 4, 1],
    });
    
    const ascendingNumbers = await app.resolve(query(ref('numbers'), withTransforms([
      sort(ascending((item) => item)),
    ], entries())));
    // ascendingNumbers === [1, 2, 3, 4, 5]
    
    const descendingNumbers = await app.resolve(query(ref('numbers'), withTransforms([
      sort(descending((item) => item)),
    ], entries())));
    // descendingNumbers === [5, 4, 3, 2, 1]

    This example shows how to apply the most basic sort transform. Although the sort officially takes an array of sort orders, you can still define a sort with a single sortOrder.

    Note that the ascending and descending node factories are called with a function returning its parameter (same as identity from lodash). You might expect that this function receives an instance of the item, but that's not the case. In fact this function is a factory function that gets passed into an fn node in order to create a Muster function. See the fn documentation to learn more about Muster functions. Thanks to that, Muster internally operates only on NodeDefinitions, which permits serializing these nodes to JSON and safely sending them to remote Muster instances without having to worry about running unsafe JavaScript code on the server.

    example

    Sorting branches

    import muster, {
      ascending,
      descending,
      get,
      entries,
      key,
      query,
      ref,
      sort,
      withTransforms,
    } from '@dws/muster';
    
    const app = muster({
      cars: [
        { make: 'Mercedes', model: 'C 63 AMG', year: 2017 },
        { make: 'Mercedes', model: 'A', year: 2009 },
        { make: 'Audi', model: 'R8', year: 2013 },
        { make: 'Audi', model: 'A4', year: 2018 },
        { make: 'Toyota', model: 'Corolla', year: 2016 },
      ],
    });
    
    const sortedCars = await app.resolve(query(ref('cars'), withTransforms([
      sort([
        ascending((car) => get(car, 'make')),
        descending((car) => get(car, 'year')),
      ]),
    ], entries({
      make: key('make'),
      model: key('model'),
      year: key('year'),
    }))));
    // sortedCars = [
    //   { make: 'Audi', model: 'A4', year: 2018 },
    //   { make: 'Audi', model: 'R8', year: 2013 },
    //   { make: 'Mercedes', model: 'C 63 AMG', year: 2017 },
    //   { make: 'Mercedes', model: 'A', year: 2009 },
    //   { make: 'Toyota', model: 'Corolla', year: 2016 },
    // ]

    This example shows how to implement a transform that sorts by the given leaves of a branch. It shows the implementation of the example that was featured in the description of the sort.

    Parameters

    Returns SortNodeDefinition

sortOrder

split

  • Creates a new instance of a split node, which is used for splitting a string by a given separator. The node expects the subject and separator to be a value containing a string value. The split can optionally define a limit - a value containing a numeric value. It works in a similar way to the String.split.

    example

    Split a string

    import muster, { split } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(split(
      'The quick brown fox jumps over the lazy dog',
      ' ',
    ));
    // === [
    //   'The',
    //   'quick',
    //   'brown',
    //   'fox',
    //   'jumps',
    //   'over',
    //   'the',
    //   'lazy',
    //   'dog',
    // ];

    Parameters

    Returns SplitNodeDefinition

sqrt

  • Creates a new instance of a sqrt node, which is a type of NodeDefinition used to compute a square root of a given number for number-based values.

    example

    Square root of four

    import muster, { sqrt, ref } from '@dws/muster';
    
    const app = muster({
      four: 4,
    });
    
    const result = await app.resolve(sqrt(ref('four')));
    // result === 2

    This example shows how to use sqrt node.

    Parameters

    Returns SqrtNodeDefinition

startCase

  • Creates a new instance of a [[startCased]] node, which is used when converting a string to a start case string. The node expects the subject to be a value that contains a string value. It works in a similar way to the startCase method from lodash: https://lodash.com/docs/4.17.4#startCase

    example

    Convert string to start case

    import muster, { startCase } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(startCase('Hello World'));
    // === 'Hello World'
    
    await app.resolve(startCase('hello world'));
    // === 'Hello World'
    
    await app.resolve(startCase('HELLO world'));
    // === 'HELLO World'

    Parameters

    Returns StartCaseNodeDefinition

startRequest

startRequestRetryLoop

startsWith

  • Creates a new instance of a startsWith node, which is used when checking if a given string starts with a given pattern. The node expects the subject and the pattern to be a value containing a string value.

    example

    Check if a string starts with a pattern

    import muster, { startsWith } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(startsWith('Hello world', 'He'));
    // === true
    
    await app.resolve(startsWith('Hello world', 'abc'));
    // === false

    Parameters

    Returns StartsWithNodeDefinition

stateful

  • Creates a new instance of a stateful node, which is useful when you need to create a graph node that can be changed from outside Muster. It works in the same way as a fromStream with the BehaviourSubject from RxJS.

    example

    Simple stateful node

    import muster, { computed, ref, stateful } from '@dws/muster';
    
    const isOffline = stateful(false);
    const app = muster({
      isOffline,
      status: computed([ref('isOffline')], (isOffline) =>
        isOffline ? 'Offline' : 'Online',
      ),
    });
    
    app.resolve(ref('status')).subscribe((status) => {
      console.log(status);
    });
    
    console.log('Changing isOffline to true');
    isOffline.update(true);
    
    // Console output:
    // Online
    // Changing isOffline to true
    // Offline

    This example shows how to use a stateful to send values to Muster.

    Type parameters

    • V

    Parameters

    • initialValue: V

    Returns ExternalStatefulNodeDefinition<V>

step

stepNext

stepThrow

string

  • string(value: string): string

strlen

  • Creates a new instance of a strlen node, which is used when computing the length of a given string. When evaluated this node resolves to a numeric value containing a length of the string.

    deprecated
    example

    Compute the length of a string

    import muster, { computed, ref, strlen } from '@dws/muster';
    
    const app = muster({
      someString: 'Hello world!',
      first: 'Bob',
      last: 'Marley',
      computedString: computed([ref('first'), ref('last')], (first, last) => `${first} ${last}`),
    });
    
    await app.resolve(strlen('123456789')); // === 9
    await app.resolve(strlen(ref('someString'))); // === 12
    await app.resolve(strlen(ref('computedString'))); // === 10

    Parameters

    Returns NodeDefinition

Const stubTrue

  • stubTrue(): boolean

subject

subscribe

substring

  • Creates a new instance of a substring node, which is used when extracting a part of a given string. The node expects the subject to be a value containing a string value. It also requires a startIndex, which must be a value containing a numeric value. End index is optional and should also be a value containing a numeric value. It works in a similar way to the String.substring from JS.

    example

    Extract a substring

    import muster, { substring } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(substring(
      'Hello world',
      1,
    ));
    // === 'ello world'
    
    await app.resolve(substring(
      'Hello world',
      0,
      5,
    ));
    // === 'Hello'

    Parameters

    Returns SubstringNodeDefinition

subtract

  • Creates a new instance of a subtract node, which is a type of NodeDefinition used to compute the difference between multiple number-based values. The subtract node takes any number of operands. It will throw an error if the number of operands is below 2 as it doesn't make sense to do the subtraction operation with a single operand.

    example

    Subtract two numbers

    import muster, { ref, subtract } from '@dws/muster';
    
    const app = muster({
      five: 5,
      three: 3,
    });
    
    const result = await app.resolve(
      subtract(ref('five'), ref('three')),
    );
    // result === 2

    This example shows how to compute a difference between 5 and 3 with the use of a subtract node.

    example

    Subtract five numbers

    import muster, { add, computed, ref, subtract, variable } from '@dws/muster';
    
    const app = muster({
      five: 5,
      four: computed([], () => 4),
      three: variable(3),
      two: add(ref('one'), ref('one')),
      one: 1,
    });
    
    const result = await app.resolve(
      subtract(ref('five'), ref('four'), ref('three'), ref('two'), ref('one')),
      // Same as 5-4-3-2-1 in JS
    );
    // result === -5

    This example shows how to subtract five differently computed numbers. As mentioned in the description above, this node can handle any number of operands as long as they resolve to a numeric value.

    Parameters

    Returns SubtractNodeDefinition

supportsAddItemAtOperation

supportsCallOperation

supportsClearOperation

supportsContainsOperation

supportsEvaluateOperation

supportsGetChildOperation

supportsGetItemsOperation

supportsInitOperation

supportsIsPendingOperation

supportsIsUpdatingOperation

  • supportsIsUpdatingOperation<T, P, S, D, V>(node: NodeDefinition): boolean
  • supportsIsUpdatingOperation<T, P, S, D, V>(node: GraphNode): boolean
  • supportsIsUpdatingOperation<T, P, S, D, V>(node: NodeDefinition | GraphNode): boolean

supportsIterateOperation

supportsLengthOperation

supportsOperationType

supportsPopOperation

supportsPushOperation

supportsRemoveItemAtOperation

  • supportsRemoveItemAtOperation<T, P, S, D, V>(node: NodeDefinition): boolean
  • supportsRemoveItemAtOperation<T, P, S, D, V>(node: GraphNode): boolean
  • supportsRemoveItemAtOperation<T, P, S, D, V>(node: NodeDefinition | GraphNode): boolean

supportsRemoveItemOperation

  • supportsRemoveItemOperation<T, P, S, D, V>(node: NodeDefinition): boolean
  • supportsRemoveItemOperation<T, P, S, D, V>(node: GraphNode): boolean
  • supportsRemoveItemOperation<T, P, S, D, V>(node: NodeDefinition | GraphNode): boolean

supportsRemoveItemsOperation

  • supportsRemoveItemsOperation<T, P, S, D, V>(node: NodeDefinition): boolean
  • supportsRemoveItemsOperation<T, P, S, D, V>(node: GraphNode): boolean
  • supportsRemoveItemsOperation<T, P, S, D, V>(node: NodeDefinition | GraphNode): boolean

supportsRequestOperation

supportsResetOperation

supportsResolveOperation

supportsResultOperation

supportsSetOperation

supportsShiftOperation

supportsStepOperation

supportsTransformItemsOperation

  • supportsTransformItemsOperation<T, P, S, D, V>(node: NodeDefinition): boolean
  • supportsTransformItemsOperation<T, P, S, D, V>(node: GraphNode): boolean
  • supportsTransformItemsOperation<T, P, S, D, V>(node: NodeDefinition | GraphNode): boolean

supportsUnshiftOperation

switchMap

  • switchMap<V, T>(project: function, stream: Stream<V>): Stream<T>

switchOn

  • Creates a new instance of a switchOn node, which is used to conditionally return a different value. It works in a similar way to the ifElse node, but allows for a more concise definition when defining more than one condition.

    The conditions are defined with the help of [[case]] and otherwise nodes. Each switchOn can define any number of [[case]] cases, and MUST define exactly one otherwise node.

    example

    Simple switchOn node

    import muster, { otherwise, ref, switchOn, variable, when } from '@dws/muster';
    
    const app = muster({
      productType: variable(1),
      productTypeName: switchOn(ref('productType'), [
        when(1, 'Vegetable'),
        when(2, 'Meat'),
        when(3, 'Frozen'),
        otherwise('Unknown'),
      ]),
    });
    
    await app.resolve(ref('productTypeName')); // === 'Vegetable'
    example

    switchOn with dynamic values

    import muster, {
      computed,
      match,
      otherwise,
      param,
      ref,
      switchOn,
      types,
      variable,
      when,
    } from '@dws/muster';
    
    const app = muster({
      productType: variable(1),
      productTypeName: switchOn(ref('productType'), [
        when(1, ref('currentLocale', 'productType.vegetable')),
        when(2, ref('currentLocale', 'productType.meat')),
        when(3, ref('currentLocale', 'productType.frozen')),
        otherwise(ref('currentLocale', 'productType.unknown')),
      ]),
      currentLocale: ref('locales', ref('currentLocaleName')),
      currentLocaleName: variable('en-GB'),
      locales: {
        [match(types.string, 'language')]: {
          [match(types.string, 'key')]: computed([param('language'), param('key')], (lang, key) => {
             // TODO: Extract correct value from some locale file
             return 'test';
          }),
        },
      },
    });
    
    await app.resolve(ref('productTypeName')); // === 'test'
    example

    switchOn with dynamic cases

    import muster, { otherwise, ref, switchOn, variable, when } from '@dws/muster';
    
    const app = muster({
      productType: variable(1),
      productTypeName: switchOn(ref('productType'), [
        when(ref('productTypes', 'vegetable'), 'Vegetable'),
        when(ref('productTypes', 'meat'), 'Meat'),
        when(ref('productTypes', 'frozen'), 'Frozen'),
        otherwise('Unknown'),
      ]),
      productTypes: {
        vegetable: 1,
        meat: 2,
        frozen: 3,
      },
    });
    
    await app.resolve(ref('productTypeName')); // === 'Vegetable'
    example

    switchOn with pattern matching

    import muster, {
      format,
      gte,
      otherwise,
      pattern,
      ref,
      switchOn,
      variable,
      when,
    } from '@dws/muster';
    
    const app = muster({
      subscribersCount: variable(15),
      subscribers: switchOn(ref('subscribers'), [
        when(0, 'No subscribers'),
        when(pattern((_) => gte(_, 1000)), 'Thousands of subscribers'),
        when(pattern((_) => gte(_, 100)), 'Hundreds of subscribers'),
        when(pattern((_) => gte(_, 30)), 'Many subscribers'),
        otherwise(format('${count} subscribers', { count: ref('subscribers') })),
      ]),
    });
    
    await app.resolve(ref('subscribers')); // === '15 subscribers'

    Parameters

    Returns SwitchOnNodeDefinition

take

  • Creates a new instance of a take node, which is a type of collection transform used when limiting the number of items returned from a collection. It works in a similar way to the slice, but it cannot change the offset.

    example

    Take first item

    import muster, { entries, query, ref, take, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
    });
    
    const firstNumber = await app.resolve(query(ref('numbers'), withTransforms([
      take(1),
    ], entries())));
    // firstNumber === [1]

    This example shows how to use the take to extract the first item of a collection. The count doesn't have to be a constant. In this particular example, the value is being converted internally to a value node. This means you can use any other node as the count.

    example

    Configurable count

    import muster, { entries, query, ref, set, take, variable, withTransforms } from '@dws/muster';
    
    const app = muster({
      numbers: [1, 2, 3, 4, 5],
      numbersToTake: variable(1),
    });
    
    app.resolve(query(ref('numbers'), withTransforms([
      take(ref('numbersToTake')),
    ], entries()))).subscribe((numbers) => {
      console.log(numbers);
    });
    
    console.log('Change numbersToTake to 3');
    await app.resolve(set('numbersToTake', 3));
    
    // Console output:
    // [1]
    // Change numbersToTake to 3
    // [1, 2, 3]

    This example shows how to use a variable node to define the number of items to take.

    Parameters

    Returns TakeNodeDefinition

takeFirst

takeLast

  • Creates a new instance of a takeLast node, which works in a similar way to the series node, but instead of resolving all operations as its dependencies, it subscribes to all of them through the store. This prevents these operations from being added to the dependency chain of the takeLast node. This node is internally used by the proxy node to disconnect the middleware subscription from the output of the proxy node.

    Parameters

    Returns TakeLastNodeDefinition

takeUntilPredicate

  • takeUntilPredicate<T>(predicate: function, stream: Stream<T>): Stream<T>

tap

test

  • Creates a new instance of a test node, which is used when checking if a given regular expression matches a given subject. It works in a similar way to RegExp.test from JavaScript.

    example

    Check if a regex matches a string

    import muster, { regex, test } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(test(regex(/\d+/), '1'));
    // === true
    
    await app.resolve(test(regex(/\d+/), '123'));
    // === true
    
    await app.resolve(test(regex(/\d+/), 'asdf'));
    // === false

    Parameters

    Returns TestNodeDefinition

thenable

  • thenable<T>(stream: ObservableLike<T>): ObservableLike<T> & Promise<T>

toBase64

  • Creates a new instance of a toBase64 node, which is used when converting a string to a base64 encoded string The node expects the subject to be a value that contains a string value.

    example

    Convert the string to Base64

    import muster, { toBase64 } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(toBase64('Hello world'));
    // === 'SGVsbG8gd29ybGQ='

    This example shows how to convert a string to a base64 string.

    Parameters

    Returns ToBase64NodeDefinition

toGraphNodesWithIndices

toGraphWithMetadata

toItemsArray

toIteratorResult

toNode

toNodeDefinitionArray

toNodeDefinitionArray

toObservable

  • toObservable<T>(stream: Stream<T>): ObservableLike<T>

toRegex

toString

  • Creates a new instance of a toString node, which is used when converting a any type value to a stringified version of the value. It uses the toString helper from lodash to do the conversion. The node expects the subject to be a value containing a string value.

    example

    Convert to string

    import muster, { toString } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(toString('Hello world'));
    // === 'Hello world'
    
    await app.resolve(toString(123));
    // === '123'
    
    await app.resolve(toString(true));
    // === 'true'
    
    await app.resolve(toString({ hello: 'world'}));
    // === '[object Object]'

    Parameters

    Returns ToStringNodeDefinition

toValue

toValueOrGraphNode

transduce

transformItems

transformResponseMiddleware

transformResult

traverse

tree

  • Creates a new instance of a tree node, which is a node defining a single tree level. It implements the NodeType.getChild method which enables the use of paths when traversing a Muster graph.

    In most cases, trees are defined as an array of string matchers, with every tree having a unique name matcher. See the "Simple tree" example.

    tree also allows for dynamic tree names that use the match helper to generate a typed matcher. See the "Tree matchers" example for more information.

    This node is serializable.

    example

    Simple trees

    import { tree, value } from '@dws/muster';
    
    const myTree = tree({
      firstName: value('Bob'),
      lastName: value('Builder'),
    });

    In this example we have created a tree with two string-based tree matchers:

    • firstName
    • lastName

    The content of each tree can be any NodeDefinition. In this example, both of these trees contain values.

    To access the contents of the firstName tree we'd first have to place it in a muster graph.

    import muster, { tree, value } from '@dws/muster';
    
    const myTree = tree({
      firstName: value('Bob'),
      lastName: value('Builder'),
    });
    
    const app = muster(myTree);

    As it happens, we chose to place our tree in the root of the muster graph. Then we can just make a query for first name:

    import muster, { tree, ref, value } from '@dws/muster';
    
    const myTree = tree({
      firstName: value('Bob'),
      lastName: value('Builder'),
    });
    
    const app = muster(myTree);
    
    const firstNameValue = await app.resolve(ref('firstName'));
    // firstNameValue === 'Bob'

    See the muster helper documentation for more information on how to create an instance of muster.

    example

    Nested trees

    import muster, { tree, ref, value } from '@dws/muster';
    
    const app = muster(tree({
      currentUser: tree({
        firstName: value('Bob'),
        lastName: value('Builder'),
      }),
    }));
    
    const firstNameValue = await app.resolve(ref('currentUser', 'firstName'));
    // firstNameValue === 'Bob'

    As mentioned before, the content tree's tree can be any NodeDefinition. This allows for the creation of nested trees.

    In this example we have created a tree currentUser which contains a tree with two leaves: firstName and lastName.

    To access firstName from the currentUser we can use a ref and just specify the full path: ref('currentUser', 'firstName').

    example

    Computed trees

    import muster, { tree, computed, ref, value } from '@dws/muster';
    
    const app = muster(tree({
      name: value('Bob'),
      currentUser: computed([ref('name')], (name) =>
        tree({
          firstName: value(name),
        }),
      ),
    }));
    
    const firstName = await app.resolve(ref('currentUser', 'firstName'));
    // firstName === 'Bob'

    Trees in muster do not have to be defined at the time of creation of the muster instance. New trees can be created as a result of resolving different NodeDefinitions. In this example we have created a dynamic tree from a computed.

    See the computed documentation for more information about computed nodes.

    example

    Tree matchers

    import muster, { tree, match, param, ref, types } from '@dws/muster';
    
    const app = muster(tree({
     [match(types.string, 'treeName')]: param('treeName'),
    }));
    
    const hello = await app.resolve(ref('hello'));
    // hello === 'hello'
    
    const world = await app.resolve(ref('world'));
    world === 'world'
    
    const stringOfNumbers = await app.resolve(ref('123'));
    // stringOfNumbers === '123'
    
    const numeric = await app.resolve(ref(123));
    // numeric === 'Invalid child name: 123'

    So far we've defined trees with pre-defined, static names. tree enables one more way of defining trees: using a tree matcher. See match for more information on matcher syntax and types about supported muster type matchers.

    In this example we've created a tree with a matcher allowing for every string path. The content of this tree is a param. See the param documentation for more information about that node.

    Below the application definition we tried to retrieve four tree names:

    • string 'hello' - returned value('hello')
    • string 'world' - returned value('world')
    • string '123' - returned value('123')
    • number 123 - returned an error as the numeric name was not matched by this type matcher

    Note the tree matcher has two arguments:

    • types.string
    • 'treeName' The second argument defines the name of the parameter to define on the resolution context when the tree name gets matched by this matcher.

    This parameter can then be used in every node belonging to that tree.

    example

    Shape matchers

    import muster, { match, param, ref, tree, types, value } from '@dws/muster';
    
    const app = muster({
      [match(types.shape({ name: types.string }), 'obj')]: param('obj'),
    });
    
    const test = await app.resolve(ref(value({ name: 'test name' })));
    // test === { name: 'test name' }
    
    const testWithExtra = await app.resolve(
      ref(value({ name: 'test name', extra: 'extra prop' })),
    );
    // testWithExtra === { name: 'test name', extra: 'extra prop' }
    
    const notFoundNode = await app.resolve(ref(value({ extra: 'extra prop' })));
    // notFoundNode === 'Invalid child name: {extra: "extra prop"})'

    Tree matchers need not operate only on primitive types. With the use of a shape matcher we can define more complex matchers allowing more data to be squeezed into a single path entry. See match documentation for more information.

    example

    Using tree parameters

    import muster, { computed, match, param, ref, tree, types, value } from '@dws/muster';
    
    const app = muster({
      users: tree({
        [match(types.number, 'userId')]: computed([param('userId')], (userId) => {
          // Synchronously retrieve the user from some data source
          // or in our case - return a test tree
          return tree({
            id: value(userId),
            firstName: value(`User ${userId}`),
          });
        }),
      }),
    });
    
    const userId = await app.resolve(ref('users', 1, 'id'));
    const userFirstName = await app.resolve(ref('users', 1, 'firstName'));
    // userId === 1
    // userFirstName === 'User 1'
    
    const invalidName = await app.resolve(ref('users', 'testId', 'firstName'));
    // invalidName === 'Invalid child key: testId'

    Tree matchers are a good way of creating gateways between muster and an external API.

    To handle asynchronous requests one could replace the computed with a fromPromise and request the data asynchronously

    Parameters

    • branches: Array | object

    Returns TreeNodeDefinition

treeToObject

trim

  • Creates a new instance of a trim node, which is used for trimming white-spaces from the string-based values. The node expects the subject to be a value containing a string value. It works in a similar way to the String.trim method from JS.

    example

    Trim a string

    import muster, { trim } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(trim('  Hello world  '));
    // === 'Hello world'
    
    await app.resolve(trim('Hello world'));
    // === 'Hello world'

    Parameters

    Returns TrimNodeDefinition

trueFallback

  • trueFallback(): boolean

truncate

  • Creates a new instance of a truncate node, which is used for truncating a string to a given length. The node expects the subject to be a value containing a string value. It works in the same way as truncate from lodash. By default, the omission is configured to ... but it can be changed.

    example

    Truncate a string

    import muster, { truncate } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(truncate('Hello world', 5));
    // === 'He...'
    
    await app.resolve(truncate('Hello world', 8));
    // === 'Hello...'
    
    await app.resolve(truncate('Hello world', 6, '+'));
    // === 'Hello+'
    
    await app.resolve(truncate('Hello world', 8, '+'));
    // === 'Hello w+'

    Parameters

    Returns TruncateNodeDefinition

type

uniqBy

  • uniqBy<T>(iteratee: function, queue: Queue<T>): Array<T>
  • Type parameters

    • T

    Parameters

    • iteratee: function
        • (value: T): string
        • Parameters

          • value: T

          Returns string

    • queue: Queue<T>

    Returns Array<T>

unique

  • Creates a new instance of a unique node, a collection transform that creates a duplicate-free version of an array (using SameValueZero for equality comparisons) in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array.

    unique accepts an optional predicate used to identify sub-properties of items to use in comparison.

    example

    Simple usage

    import muster, { applyTransforms, unique, entries, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: applyTransforms(
        [1, 2, 3, 1, 2],
        [unique()],
      ),
    });
    
    const uniqueNumbers = await app.resolve(query(ref('numbers'), entries()));
    // uniqueNumbers === [1, 2, 3]

    This example shows how to apply unique to a collection.

    example

    Usage with predicates

    import muster, { applyTransforms, unique, get, entries, key, query, ref } from '@dws/muster';
    
    const app = muster({
      books: applyTransforms(
        [
          { title: 'Casino Royale', author: 'Ian Fleming', year: 1953 },
          { title: 'Live and Let Die', author: 'Ian Fleming', year: 1953 },
          { title: 'The Big Four', author: 'Agatha Christie', year: 1927 },
        ],
        [
          unique((book) => get(book, 'year')),
        ],
      ),
    });
    
    const publishingYears = await app.resolve(query(ref('books'), entries({
      year: key('year'),
    })));
    // publishingYears === [
    //   { year: 1953 },
    //   { year: 1927 },
    // ]

    This example demonstrates how to use a predicate to identify an item property to use for unique comparison.

    Parameters

    Returns UniqueNodeDefinition

Let unitTestMatcher

  • unitTestMatcher(): false

unmetConditionErrorMessage

  • unmetConditionErrorMessage(node: GraphNode): string

unshift

  • Creates an instance of an unshift, which is a type of a graph node used when unshifting a new item into a mutable collection. It works in a similar way to Array.unshift(...) function from JavaScript.

    example

    Unshift a number to a mutable collection

    import muster, { arrayList, entries, unshift, query, ref } from '@dws/muster';
    
    const app = muster({
      numbers: arrayList([1, 2, 3]),
    });
    
    app.resolve(query(ref('numbers'), entries())).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(unshift(ref('numbers'), 5));
    
    // Console output:
    // [1, 2, 3]
    // [5, 1, 2, 3]

    This example shows how to add a new item at the beginning of a mutable collection.

    example

    Unshift a branch to a mutable collection

    import muster, { arrayList, entries, key, unshift, query, ref, toNode } from '@dws/muster';
    
    const app = muster({
      people: arrayList([
        { firstName: 'Lizzie', lastName: 'Ramirez' },
        { firstName: 'Charlotte', lastName: 'Schneider' },
      ]),
    });
    
    app.resolve(query(ref('people'), entries({
      firstName: key('firstName'),
    }))).subscribe((value) => {
      console.log(value);
    });
    
    await app.resolve(
      unshift(ref('people'), toNode({ firstName: 'Genevieve', lastName: 'Patrick' })),
    );
    
    // Console output:
    // [{ firstName: 'Lizzie' }, { firstName: 'Charlotte' }]
    // [{ firstName: 'Genevieve' }, { firstName: 'Lizzie' }, { firstName: 'Charlotte' }]

    This example shows how to add a new branch at the beginning of a mutable collection.

    Parameters

    Returns UnshiftNodeDefinition

unshiftOperation

untilBooleanValueNode

untilDynamicNode

untilIntegerValueNode

untilNumberValueNode

untilPositiveIntegerValueNode

untilRegexNode

untilStatefulValueNode

untilStringValueNode

untilValueNode

unwrapResult

update

  • Creates a new instance of a update node, which is used when updating a value of a settable node to a new value, which is based on a previous value of that settable node. It works in a similar way to the set but instead of setting a value to a pre-defined value, it can compute the value to set based on the current value of the settable node. You can think of it as setState from React. The updater function can be any NodeDefinition that implements a call operation, e.g. action and fn, and it should resolve to a NodeDefinition. That node will then be set as a value of the settable node.

    Parameters

    Returns UpdateNodeDefinition

  • Creates a new instance of a update node, which is used when updating a value of a settable node to a new value, which is based on a previous value of that settable node. It works in a similar way to the set but instead of setting a value to a pre-defined value, it can compute the value to set based on the current value of the settable node. You can think of it as setState from React. The updater function can be any NodeDefinition that implements a call operation, e.g. action and fn, and it should resolve to a NodeDefinition. That node will then be set as a value of the settable node.

    Parameters

    Returns UpdateNodeDefinition

  • Creates a new instance of a update node, which is used when updating a value of a settable node to a new value, which is based on a previous value of that settable node. It works in a similar way to the set but instead of setting a value to a pre-defined value, it can compute the value to set based on the current value of the settable node. You can think of it as setState from React. The updater function can be any NodeDefinition that implements a call operation, e.g. action and fn, and it should resolve to a NodeDefinition. That node will then be set as a value of the settable node.

    Parameters

    Returns UpdateNodeDefinition

  • Creates a new instance of a update node, which is used when updating a value of a settable node to a new value, which is based on a previous value of that settable node. It works in a similar way to the set but instead of setting a value to a pre-defined value, it can compute the value to set based on the current value of the settable node. You can think of it as setState from React. The updater function can be any NodeDefinition that implements a call operation, e.g. action and fn, and it should resolve to a NodeDefinition. That node will then be set as a value of the settable node.

    Parameters

    Returns UpdateNodeDefinition

upgradeGraph

upperCase

  • Creates a new instance of a upperCase node, which is used when converting a string to an upper case string. The node expects the subject to be a value that contains a string value. It works in a similar way to the String.toUpperCase method in JavaScript.

    example

    Convert string to upper case

    import muster, { upperCase } from '@dws/muster';
    
    const app = muster({});
    
    await app.resolve(upperCase('Hello World'));
    // === 'HELLO WORLD'

    Parameters

    Returns UpperCaseNodeDefinition

value

  • Creates a new instance of the value node, which is used for storing raw data and for sending data to other nodes.

    Use value helper to make new instance of this node.

    This node is serializable and allowed to send over-the-wire to remote instances of muster. To find out more about node serialization visit the serialize documentation. Additionally, check out proxy and remote for more information on how remote query execution works.

    example

    Creating instances of this node

    import { value } from '@dws/muster';
    
    value('Hello world');      // Create a value node storing a string
    value(123);                // Create a value node storing a number
    value({ hello: 'world' }); // Create a value node storing an object
    example

    Sending values to computed nodes

    import { computed, value } from '@dws/muster';
    
    computed(
      [value('Hello'), value('world')],
      (left, right) => `${left} ${right}`,
    );

    In this example we have created a computed node whose task is to combine two values, left and right, into one string containing both of these values separated by a space. Note the value nodes are passed into the dependency section of the computed node. In this example they serve as static data. One thing to note is that in this example there's one more value node being implicitly created. Because everything in muster graph must be a node, the return value of the computed node is converted to a value node.

    More explicit definition of this computed node could look like this:

    import { computed, value } from '@dws/muster';
    
    computed(
      [value('Hello'), value('world')],
      (left, right) => value(`${left} ${right}`),
    );

    To find out more about the computed, visit its documentation.

    Type parameters

    • T

    Parameters

    • data: T

    Returns ValueNodeDefinition<T>

valueOf

valuesAreEqual

variable

  • Creates a new instance of a variable node, which is a node that can store values. Its read and write process is synchronous. Each variable node has an [[initialValue]] that defines both the node's starting value and its fallback when reset. See the reset and "Resetting variables" example to learn more about resetting variables.

    Each muster instance has a separate node cache. This cache stores the latest resolved value of a NodeDefinition for as long as there's something in the application that holds a subscription to it. By default Muster does not store the values for every node. The act of subscribing to a node (assuming it's a dynamic node) makes a new entry in the node cache. One beneficial side effect of having this node cache is higher performance. An entry in the application cache can be used in a case where some other part of the application requests the value for a node that already has an open subscription. To save some computation Muster can then just retrieve a value from the node cache instead of trying to re-calculate the value. Each node cache entry holds a subscription count. When the count reaches 0 muster removes the value from the node cache.

    A variable taps into this behaviour whenever a value is set to it. The act of storing a value in a variable makes a new entry in the node cache and artificially increases the subscription count for that entry. This means that the variable does not clear its value when the subscription count reaches 0. In order for the variable to clear its value we have to force it to reset. We do that with the help of a reset. See "Resetting variables" example to learn more about this.

    example

    Basic variable

    import muster, { ref, set, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
    });
    
    console.log('Retrieving a name');
    app.resolve(ref('name')).subscribe((name) => {
      console.log(`Name: ${name}`);
    });
    
    console.log('Setting a name to John');
    await app.resolve(set('name', 'John'));
    
    // Console output:
    // Retrieving a name
    // Name: Bob
    // Setting a name to John
    // Name: John

    This example demonstrates how the variable node can be accessed and how to change its value. See the set documentation for more information about how set works. Contrary to how it might look, the process of setting the value of a [[variabled]] is completely synchronous. The reason why the await keyword is used when setting is because the resolve method returns an object implementing both the Observable and Promise APIs. This is because Muster allows for the graph to be spread across multiple different environments. This means that parts of the graph can exist on a remote server and accessing them is not a synchronous process. Learn more about this in the remote and proxy documentation.

    example

    Using variables in a computed node

    import muster, { computed, ref, set, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
      greeting: computed([ref('name')], (name) => `Hello ${name}`),
    });
    
    console.log('Retrieving a greeting');
    app.resolve(ref('greeting')).subscribe((greeting) => {
      console.log(greeting);
    });
    
    console.log('Setting a name to Jane');
    await app.resolve(set('name', 'Jane'));
    
    // Console output:
    // Retrieving a greeting
    // Hello Bob
    // Setting a name to Jane
    // Hello Jane
    example

    Persistence of stored value

    import muster, { ref, set, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
    });
    
    console.log('Retrieving a name');
    const nameSubscription = app.resolve(ref('name')).subscribe((name) => {
      console.log(name);
    });
    
    console.log('Setting a name to Jane');
    await app.resolve(set('name', 'Jane'));
    
    console.log('Unsubscribing from name');
    nameSubscription.unsubscribe();
    
    app.resolve(ref('name')).subscribe((name) => {
      console.log(`Re-subscribed name: ${name}`);
    });
    
    // Console output:
    // Retrieving a name
    // Bob
    // Setting a name to Jane
    // Jane
    // Unsubscribing from name
    // Re-subscribed name: Jane

    This example presents the persistence of variable value even after losing all subscriptions.

    example

    Resetting variables

    import muster, { ref, reset, set, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob'),
    });
    
    app.resolve(ref('name')).subscribe((name) => {
      console.log(name);
    });
    
    console.log('Changing name to Jane');
    await app.resolve(set('name', 'Jane'));
    
    console.log('Resetting name');
    await app.resolve(reset('name'));
    
    // Console output:
    // Bob
    // Changing name to Jane
    // Jane
    // Resetting name
    // Bob

    This example shows how to restore the variable to its initial value with the help of a reset.

    example

    Variable validators

    import muster, { set, types, variable } from '@dws/muster';
    
    const app = muster({
      name: variable('Bob', types.string),
    });
    
    await app.resolve(set('name', 'Kate')); // OK
    
    await app.resolve(set('name', 123)); // Error

    Optionally, the variable node can also define a value validator using Muster types.

    Parameters

    • initialValue: NodeLike
    • Default value validator: Matcher<any, any> = types.any

    Returns VariableNodeDefinition

when

withContext

  • Creates a new instance of a withContext node, which is used when there's a need of storing some data on the context. Used internally by the hoistDependencies utility when sending the data to the remote muster instance.

    example

    Store and access data from context

    import muster, { computed, context, ref, value, withContext } from '@dws/muster';
    
    const app = muster({
      inner: withContext({
        name: value('Bob'),
      }, {
        greeting: computed([context('name')], (name) =>
          `Hello, ${name}`,
        ),
      }),
    });
    
    const greeting = await app.resolve(ref('inner', 'greeting'));
    // greeting === 'Hello, Bob';

    This example shows how to use the withContext to store data on the context and how to access it with the help of the context.

    Parameters

    Returns WithContextNodeDefinition

withErrorPath

withNodeContext

  • withNodeContext<S, D, A, V, T>(fn: function): function

withReducerState

withScope

  • Creates an instance of a withScope node, which evaluates an expression within the supplied target scope.

    This is typically used in combination with a scope node to restrict an arbitrary input expression's access to a predefined 'safe' portion of the graph.

    example

    Sandboxing arbitrary expressions to a scoped sub-graph

    import muster, { arrayList, call, entries, fn, push, query, ref, root, scope, withScope, value } from '@dws/muster';
    
    const app = muster({
      private: value('secret'),
      sandboxed: scope({
        todos: arrayList([]),
        addTodo: fn((item) => push(ref('todos'), item)),
      }),
    });
    
    const query1 = query(root(), {
      'todos': entries(),
    });
    app.resolve(withScope(ref('sandboxed'), query1)).subscribe((todos) => {
      console.log(todos);
    });
    // Console output:
    // []
    
    const query2 = call('addTodo', ['First item']);
    await withScope(ref('sandboxed'), query2);
    // Console output:
    // ['First item']
    
    const query3 = ref('private');
    await withScope(ref('sandboxed'), query3); // Throws error: "Invalid child key: "private""

    Parameters

    Returns WithScopeNodeDefinition

withScopeFrom

withTransaction

  • withTransaction<T>(scope: Scope, fn: function): void

withTransforms

withUniqueId

xhrMiddleware

Object literals

Const DEFAULT_QUERY_SET_OPTIONS

DEFAULT_QUERY_SET_OPTIONS: object

bubbleErrorsToTop

bubbleErrorsToTop: false = false

Const RESOLVE_NODE_SHAPE

RESOLVE_NODE_SHAPE: object

combine

combine: Matcher<undefined | Function, Matcher<Function, any>> = types.saveHash(types.func)

dependencies

dependencies: Matcher<(NodeDependency | GraphAction<string, object, any, object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>, StaticNodeType<string, object, object>, StatelessNodeType<string, object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>> | StatefulNodeType<string, object, any, object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>>>)[], Matcher<NodeDependency | GraphAction<string, object, any, object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>, StaticNodeType<string, object, object>, StatelessNodeType<string, object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>> | StatefulNodeType<string, object, any, object, object, string, GraphOperation<string, object, object, OperationType<string, object, object>>>>, any>> = types.arrayOf(types.oneOfType<NodeDependency | GraphAction>([types.shape({target: types.oneOfType<NodeDefinition | GraphNode>([graphTypes.graphNode,graphTypes.nodeDefinition,]),allowErrors: types.optional(types.bool),allowPending: types.optional(types.bool),acceptNil: types.optional(types.bool),once: types.optional(types.bool),until: types.optional(types.shape({predicate: types.saveHash(types.func),errorMessage: types.optional(types.oneOfType<string | Function>([types.string, types.saveHash(types.func)]),),}),),}),graphTypes.graphAction,]),)

Const ResolveNodeType

ResolveNodeType: object

The implementation of the resolve node. See the resolve documentation to learn more.

__computed

__computed: true = true

deserialize

deserialize: false = false as false

hash

hash: HashFunction<Object> = hash.shape(RESOLVE_NODE_SHAPE)

name

name: "resolve" = "resolve"

serialize

serialize: false = false as false

shape

shape: Matcher<Object, object> = types.shape(RESOLVE_NODE_SHAPE)

is

operations

operations: object

evaluate

evaluate: object

cacheable

cacheable: true = true

getContextDependencies

  • getContextDependencies(): Array<never>

getDependencies

run

Const TRAVERSE_NODE_SHAPE

TRAVERSE_NODE_SHAPE: object

operation

operation: Matcher<GraphOperation<string, object, object, OperationType<string, object, object>>, any> = graphTypes.graphOperation

root

root: Matcher<NodeDefinition<any, any, any, object, any, StaticNodeType<any, any, any> | StatelessNodeType<any, any, any, string, GraphOperation<string, object, object, OperationType<string, object, object>>> | StatefulNodeType<any, any, any, object, any, string, GraphOperation<string, object, object, OperationType<string, object, object>>>>, Matcher<NodeDefinition<any, any, any, object, any, StaticNodeType<any, any, any> | StatelessNodeType<any, any, any, string, GraphOperation<string, object, object, OperationType<string, object, object>>> | StatefulNodeType<any, any, any, object, any, string, GraphOperation<string, object, object, OperationType<string, object, object>>>>, any>[]> = types.oneOfType([graphTypes.nodeDefinition, graphTypes.graphNode])

Const TraverseNodeType

TraverseNodeType: object

__computed

__computed: true = true

deserialize

deserialize: false = false as false

hash

hash: HashFunction<Object> = hash.shape(TRAVERSE_NODE_SHAPE)

name

name: "traverse" = "traverse"

serialize

serialize: false = false as false

shape

shape: Matcher<Object, object> = types.shape(TRAVERSE_NODE_SHAPE)

is

operations

operations: object

evaluate

evaluate: object

cacheable

cacheable: true = true

getContextDependencies

getContextDependencies: function = constant([])

Type declaration

    • (): T
    • Returns T

getDependencies

run

Const base64Encoder

base64Encoder: object

decode

  • decode(value: string): any

encode

  • encode(value: any): string

Const identityEncoder

identityEncoder: object

decode

decode: identity = identity

encode

encode: identity = identity

Const isValidReducerStepResult

isValidReducerStepResult: object

errorMessage

predicate

Const jsonEncoder

jsonEncoder: object

decode

decode: parse = JSON.parse

encode

encode: stringify = JSON.stringify

Const shallow

shallow: object

predicate

predicate: stubTrue = stubTrue

errorMessage

  • errorMessage(): string

Const untilConditionIsValueNode

untilConditionIsValueNode: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilDataNode

untilDataNode: object

predicate

predicate: isDataNode = isDataNode

errorMessage

Const untilInputIsValueNode

untilInputIsValueNode: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilIsArrayNodeOrPendingNode

untilIsArrayNodeOrPendingNode: object

predicate

predicate: isArrayNodeOrPendingNode = isArrayNodeOrPendingNode

errorMessage

Const untilIsCollectionOrFullyResolvedNode

untilIsCollectionOrFullyResolvedNode: object

errorMessage

predicate

Const untilIsContainerOrFullyResolvedNode

untilIsContainerOrFullyResolvedNode: object

errorMessage

predicate

Const untilIsDataNode

untilIsDataNode: object

predicate

predicate: isDataNode = isDataNode

errorMessage

Const untilIsFieldsNodeOrCollectionFieldsNode

untilIsFieldsNodeOrCollectionFieldsNode: object

predicate

predicate: isFieldsNodeOrCollectionFieldsNode = isFieldsNodeOrCollectionFieldsNode

errorMessage

Const untilIsFullyResolvedNode

untilIsFullyResolvedNode: object

errorMessage

predicate

Const untilIsFullyResolvedValueNode

untilIsFullyResolvedValueNode: object

errorMessage

predicate

Const untilIsSortOrderNode

untilIsSortOrderNode: object

predicate

predicate: function = SortOrderNodeType.is

Type declaration

errorMessage

Const untilIsValidIteratorResult

untilIsValidIteratorResult: object

predicate

predicate: isValidIteratorResult = isValidIteratorResult

errorMessage

Const untilIsValidSortValue

untilIsValidSortValue: object

predicate

predicate: isValidSortValue = isValidSortValue

errorMessage

Const untilIsValueNode

untilIsValueNode: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilIsValueNodeOrKeyNode

untilIsValueNodeOrKeyNode: object

errorMessage

predicate

Const untilItemWithId

untilItemWithId: object

errorMessage

predicate

Const untilNodeSupportedByGet

untilNodeSupportedByGet: object

errorMessage

predicate

Const untilPatternIsValueNodeOrCallableNode

untilPatternIsValueNodeOrCallableNode: object

predicate

predicate: isValueNodeOrCallableNode = isValueNodeOrCallableNode

errorMessage

Const untilPlaceholderOrItems

untilPlaceholderOrItems: object

predicate

Const untilSupportsAddItemAtOperation

untilSupportsAddItemAtOperation: object

predicate

predicate: supportsAddItemAtOperation = supportsAddItemAtOperation

errorMessage

Const untilSupportsCallOperation

untilSupportsCallOperation: object

predicate

predicate: supportsCallOperation = supportsCallOperation

errorMessage

Const untilSupportsCallOperation

untilSupportsCallOperation: object

predicate

predicate: supportsCallOperation = supportsCallOperation

errorMessage

Const untilSupportsCallOperation

untilSupportsCallOperation: object

predicate

predicate: supportsCallOperation = supportsCallOperation

errorMessage

Const untilSupportsClearOperation

untilSupportsClearOperation: object

predicate

predicate: supportsClearOperation = supportsClearOperation

errorMessage

Const untilSupportsGetChildOperation

untilSupportsGetChildOperation: object

predicate

predicate: supportsGetChildOperation = supportsGetChildOperation

errorMessage

Const untilSupportsGetItemOperation

untilSupportsGetItemOperation: object

predicate

predicate: supportsGetItemsOperation = supportsGetItemsOperation

errorMessage

Const untilSupportsGetItemOperation

untilSupportsGetItemOperation: object

predicate

predicate: supportsGetItemsOperation = supportsGetItemsOperation

errorMessage

Const untilSupportsGetItemsOperation

untilSupportsGetItemsOperation: object

predicate

predicate: supportsGetItemsOperation = supportsGetItemsOperation

errorMessage

Const untilSupportsGetItemsOperation

untilSupportsGetItemsOperation: object

predicate

predicate: supportsGetItemsOperation = supportsGetItemsOperation

errorMessage

Const untilSupportsIsUpdatingOperationOrStaticNode

untilSupportsIsUpdatingOperationOrStaticNode: object

errorMessage

predicate

Const untilSupportsIterateOperation

untilSupportsIterateOperation: object

predicate

predicate: supportsIterateOperation = supportsIterateOperation

errorMessage

Const untilSupportsIterateOperation

untilSupportsIterateOperation: object

predicate

predicate: supportsIterateOperation = supportsIterateOperation

errorMessage

Const untilSupportsPopOperation

untilSupportsPopOperation: object

predicate

predicate: supportsPopOperation = supportsPopOperation

errorMessage

Const untilSupportsPushOperation

untilSupportsPushOperation: object

predicate

predicate: supportsPushOperation = supportsPushOperation

errorMessage

Const untilSupportsRemoveItemAtOperation

untilSupportsRemoveItemAtOperation: object

predicate

predicate: supportsRemoveItemAtOperation = supportsRemoveItemAtOperation

errorMessage

Const untilSupportsRemoveItemOperation

untilSupportsRemoveItemOperation: object

predicate

predicate: supportsRemoveItemOperation = supportsRemoveItemOperation

errorMessage

Const untilSupportsRemoveItemsOperation

untilSupportsRemoveItemsOperation: object

predicate

predicate: supportsRemoveItemsOperation = supportsRemoveItemsOperation

errorMessage

Const untilSupportsSetOperation

untilSupportsSetOperation: object

predicate

predicate: supportsSetOperation = supportsSetOperation

errorMessage

Const untilSupportsShiftOperation

untilSupportsShiftOperation: object

predicate

predicate: supportsShiftOperation = supportsShiftOperation

errorMessage

Const untilSupportsStepOperation

untilSupportsStepOperation: object

predicate

predicate: supportsStepOperation = supportsStepOperation

errorMessage

Const untilSupportsTransformItemsOperation

untilSupportsTransformItemsOperation: object

predicate

predicate: supportsTransformItemsOperation = supportsTransformItemsOperation

errorMessage

Const untilSupportsUnshiftOperation

untilSupportsUnshiftOperation: object

predicate

predicate: supportsUnshiftOperation = supportsUnshiftOperation

errorMessage

Const untilValidGetItemsResult

untilValidGetItemsResult: object

errorMessage

predicate

Const untilValidGetItemsResult

untilValidGetItemsResult: object

predicate

Const untilValidInitializer

untilValidInitializer: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilValidJoinOperand

untilValidJoinOperand: object

errorMessage

predicate

Const untilValidPlaceholderResult

untilValidPlaceholderResult: object

predicate

Const untilValidReducerStep

untilValidReducerStep: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilValidResult

untilValidResult: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilValidStepResult

untilValidStepResult: object

predicate

predicate: function = ValueNodeType.is

Type declaration

errorMessage

Const untilValidTargetNode

untilValidTargetNode: object

errorMessage

predicate